/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

define(
    '../entrance_ticket/Ancestor',['require','exports','module'],function(require, exports, module) {
        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };
        window.SystemDialog = (function () {
            var doHandler = null;
            var _initAlert = false;
            var _initConfirm = false;

            function initAlertDlg() {
                if (!_initAlert) {
                    if ($("#epg_alert_dlg").length == 0) {
                        $('body').append('<div id="epg_alert_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_alert_dlg").dialog({
                        title: "epg系统提醒",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    })
                    _initAlert = true;
                }
                console.log("_initAlert:" + _initAlert);
            }

            function initConfirmDlg() {
                if (!_initConfirm) {
                    if ($("#epg_confirm_dlg").length == 0) {
                        $('body').append('<div id="epg_confirm_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_confirm_dlg").dialog({
                        title: "epg系统确认",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(true);
                                }
                            },
                            {
                                text: "取消",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(false);
                                }
                            }
                        ]
                    });
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").addClass("btn btn-primary");
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").addClass("btn");
                    _initConfirm = true;
                }
                console.log("_initConfirm:" + _initConfirm);
            }

            function queryAlert(msg) {
                initAlertDlg()
                $("#epg_alert_dlg").find("div[sign=detail]").html(msg);
                $("#epg_alert_dlg").dialog("open");
            }

            function queryConfirm(msg, callback,btnNameObj) {
                initConfirmDlg();
                $("#epg_confirm_dlg").find("div[sign=detail]").html(msg);
                var btnExtend = $.extend(true,{"btn_ok":"确认","btn_cancel":"取消"},btnNameObj);
                if( "btn_ok" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").html(btnExtend["btn_ok"])
                }
                if( "btn_cancel" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").html(btnExtend["btn_cancel"])
                }
                $("#epg_confirm_dlg").dialog("open");
                doHandler = function (flag) {
                    if (typeof(callback) == "function") {
                        callback(flag);
                    }
                }
            }

            return {
                queryAlert: queryAlert,
                queryConfirm: queryConfirm
            }
        })();

    }
);
define(
    '../entrance_ticket/Ancestor.Auth',['require','exports','module'],function (require, exports, module) {
        Ancestor.Auth = (function () {
            var url = url || Com.url.parse(window.location.href)['path'];
            var baseInfo = {
                url: url,
                authUrl: '/api/permission',
                loginUrl: 'http://lego.iqiyi.com/login?url=http://lego.iqiyi.com%2F',
                url403: 'http://lego.iqiyi.com/common/403.jsp',
                loginOut: 'http://lego.iqiyi.com/logout',
                navListUrl: 'http://ulive.lego.iqiyi.com/live-web/services/liveNav.do',
                authInfo: null,
                tips: 0 //0 304页面提示 1头部标签提示
            }
            var jump2TargetPage = function (url) {
                window.location.href = url;
            }
            var getDev = function () {
                return parseInt(Com.cookie.get('dev'));
            };

            function getVersion(){
                return "4.3.172";
            }

            function setWaring(tips) {
                var warning = '<div class="alert alert-error" style="display:block;"><strong>提示!</strong> ' + tips + '</div>';
                return warning;
            }

            // ajax 请求
            var getAuthData = function (options, callback) {
                options = options || {};
                var tempBaseInfo = $.extend(true, baseInfo, options);
                Ancestor.Dao.ajax({
                    url: tempBaseInfo.authUrl,
                    dataType: 'json',
                    method: 'get',
                    cache: false,
                    //async: false,
                    data: {'uri': tempBaseInfo.url.split('?')[0]},
                    success: function (data) {
                        //console.log(data);
                        if (options.tips) {
                            //   if (baseInfo.tips) {
                            if (data.code == 'A00304')
                                callback.call(this, 1);   // 无权限
                            else
                                callback.call(this, null); // 有权限
                            return;
                        }
                        switch (data.code) {
                            case 'A00000': // 已登陆
                                tempBaseInfo.authInfo = data.data;
                                var newDev = 0;
                                if (tempBaseInfo.authInfo.devMode) {
                                    newDev = 1
                                }
                                var dev = getDev();
                                showLogInfo( baseInfo );
                                callback.call(this, "suc")
                                if (dev == NaN || dev != newDev) {
                                    Com.cookie.set('dev', newDev);
                                    window.location.reload();
                                }
                                break;
                            case 'A00303': // 未登陆
                                jump2TargetPage(tempBaseInfo.loginUrl);
                                break;

                            case 'A00304': // 无权限
                                //jump2TargetPage(baseInfo.url403);
                                var warning = setWaring('sorry,您没有操作本页面的权限！');
                                $('body').html('');
                                $('body').html(warning);
                                break;
                        }
                    },
                    error: function (data) {
                        var warning = setWaring('网络故障,<a href="javascript:void(0);" onclick = "window.location.reload();">请重刷！</a>');
                        $('body').html(warning);
                    }
                }, "/permission")

            }

            function queryNavList(baseInfo){
                var request = {};
                request.url = baseInfo.navListUrl;
                request.type = 'get';
                request.params = {};
                request.needCookie = true;
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request} , function(data){
                    if(!data) {
                        console.warn(" 获取导航条失败!")
                        return;
                    }
                    var name, items, itemName, itemUrl;
                    var navListData = [];
                    for(var nav in data){
                        name = data[nav]['name'];
                        navListData.push('<dl class="panel-live_demand clearfix"><dt><strong>' + name + '</strong></dt><dd>');
                        items = data[nav]['items'];
                        for(var item in items){
                            itemName = items[item]['name'];
                            itemUrl = items[item]['url'];
                            navListData.push('<a href="' + itemUrl + '">' + itemName +'</a>')
                        }
                        navListData.push('</dd></dl>')
                    }
                    $('#panel-nav').html(navListData.join(''));
                } )
            }

            function showLogInfo(baseInfo) {
                var header = [
                    '<div class="top">',
                    '<div class="logo">',
                    '<a href="http://lego.iqiyi.com/" alt="乐高首页"></a>',
                    '</div>',
                    '<div class="user">',
                        '<input type="hidden" name="hidden_uid" value="' + baseInfo.authInfo.uid + '">',
                        ' Hi, <a href="" class="name">' + baseInfo.authInfo.userName + '</a>&nbsp;',
                    '[<a href="http://static.lego.iqiyi.com/help/lego-help-v1.docx" class="help">帮助</a>]&nbsp;',
                        '[<a href="' + baseInfo.loginOut + '" class="help">退出</a>]',
                    '</div>',
                    '</div>',
                    '<div class="nav">',
                    '<ol>',
                    '<li class="channel-index "><a href="http://ulive.lego.iqiyi.com/live-web/home.do" class="">我的首页</a><i></i></li>',
                    '<li class="channel-catalog selected"><a href="javascript:void(0)" class="selected">直播中心</a><i></i>',
                    '<div class="panel" id="panel-nav">',
                    '</div>',
                    '</li>',
                    '</ol>',
                    '</div>'
                ].join('');
                var epg_version = auth.version() + (auth.dev() ? "_test" : "_production");
                $("header").html(header);
                $('body').append('<div class="scroll-to-top scroll-to-top-hide" id="BackToTopButton"><a class="btn" href="#">返回顶部</a></div><footer>版本 ' + epg_version + ' | Copyright ©2017 <a href="http://www.iqiyi.com" target="_blank">iQIYI.com</a></footer>');
                $(window).bind('scroll', function () {
                    Com.page.scrollToTop($("#BackToTopButton"));
                });
                queryNavList(baseInfo)
            }

            return{
                getAuthData: getAuthData,
                baseInfo: baseInfo,
                jump2TargetPage: jump2TargetPage,
                dev: getDev, //开发环境
                version:getVersion
            };
        })();
        var auth = Ancestor.Auth;
        var dev = auth.dev();
        window.auth = auth;
        window.dev = dev;
        console.log(" window.auth done");
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../entrance_ticket/Ancestor.Grid',['require','exports','module'],function (require, exports, module) {

    Ancestor.Grid = function (options) {
    };
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function (callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [
                {
                    page: 1
                }
            ]);

        },
        getParam: function () {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function () {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function () {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGridConfig: function (table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function (i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function (options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        reload: function (params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        }


    })
});


/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../entrance_ticket/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.GLOBAL =   window.GLOBAL || {};
    GLOBAL.user = {
        area: "sh"
    };
    GLOBAL.currentDate = Com.date.getCurrentDate();

    Ancestor.Config = (function() {
        var EPG_AUTH = {
            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥
        };
        return {
            EPG_AUTH: EPG_AUTH
        };
    })();

});
/**
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2017-08-15
 */
define('../entrance_ticket/Ancestor.Util',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.Ancestor = window.Ancestor || {
        version: '1.0'
    };
    Ancestor.Util = (function() {
        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        var getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };
        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            authorization: authorization,
            getUrlId: getUrlId,
            limitWordCount: limitWordCount,
            getAuth: getAuth
        };
    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../entrance_ticket/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
                var _defaultHandler = function(msg){
                    EpgWeb.Plugin.showTips({type: "error", content: msg})
                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../entrance_programEdit/Program',['require','exports','module'],function (require, exports, module) {
        window.Program = window.Program || {
            version: '1.0'
        };
        Program.Constant = {
            daoju_inner_url: "http://admin.vienx.qiyi.domain/api/partner/query.json",
            vote_inner_url: "http://vote.i.iqiyi.com/eagle/runman/query_votes",
            vote_token: "qiyi-vote-api-token-howareyou-fine3q",
            daoju_secret: auth.dev() ? '123456798' : 'LZl$UX*7bb^TTTdH$33R',
            daoju_ip: auth.dev() ? '127.0.0.1' : '10.153.108.204'
        }

    }
);
define(
    '../entrance_programEdit/Program.Action',['require','exports','module'],function (require, exports, module) {
        Program.Action = (function () {
            // 表格
            var programListGrid = null;
            var programLibraryGrid = null;
            var editForm = null;
            // 节目单列表
            var listRun = function () {
                Ancestor.Config.EPG_AUTH.list = '/program/list';
                if (!programListGrid) {
                    programListGrid = new Program.Grid($.extend(true, {
                        // '$container': $('#ChannelListContainer'),
                        type: 0
                    }, {}));
                }
                programListGrid.runDayList();
                console.log('program grid run');
            }

            var libraryRun = function () {
                Ancestor.Config.EPG_AUTH.list = '/program/list';
                if (!programLibraryGrid) {
                    programLibraryGrid = new Program.Grid($.extend(true, {
                        '$container': $('#ProgramListContainer'),
                        $grid:$('#list'),
                        type: 0
                    }, {}));
                }
                programLibraryGrid.runLibrary();
                console.log('library grid run');
            }

          //  节目新建/编目
            var editRun = function () {
                if(editForm == null){
                    editForm = new Program.Edit($.extend(true, {
                        '$form': $('form[role=form]')
                    }, {}));
                    editForm.init();
                }
                console.log(' editRun ');
            }

            return {
                listRun: listRun,
                libraryRun: libraryRun,
                editRun:editRun
            }
        })();
    }
);
///import js-src/lib/
///import js-src/com/
define('../entrance_programEdit/Program.Config',['require','exports','module'],function (require, exports, module) {
    Program.Config = $.extend({}, Ancestor.Config, {
        RECOMMEND_RATE: {
          "0": "不推荐", "1": "普通推荐", "2": "重点推荐", "3": "强烈推荐"
        },
        TABLE_COLMODEL_CONFIG: {
            qipuId: {
                name: "qipuId",
                index: 'qipuId',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.qipuId(v, o, r);
                }
            },
            pname: {
                name: "pname",
                index: 'pname',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.pname(v, o, r);
                }
            },
            playStatus:{
                name: "playStatus",
                index: 'playStatus',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.playStatus(v, o, r);
                }
            },
            startPlayTime: {
                name: "startPlayTime",
                index: 'startPlayTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            endPlayTime: {
                name: "endPlayTime",
                index: 'endPlayTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            type: {
                name: "type",
                index: 'type',
                title: false,
                width: 100,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.type(v, o, r);
                }
            },
            bossStatus: {
                name: "bossStatus",
                index: 'bossStatus',
                title: false,
                width: 90,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.bossStatus(v, o, r);
                }
            },
            episodeGrade: {
                //wait to do
                index: "episodeGrade",
                name: "episodeGrade",
                title: false,
                width: 80,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.episodeGrade(v, o, r);
                }
            },
            channelName: {
                name: "channelName",
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.channelName(v, o, r);
                }
            },

            onlineStatus: {
                name: "onlineStatus",
                index: 'onlineStatus',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.onlineStatus(v, o, r);
                }
            },
            formal: {
                name: "formal",
                index: 'formal',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.formal(v, o, r);
                }
            },

            updateTime: {
                name: "updateTime",
                index: 'updateTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            operate: {
                name: "operate",
                title: false,
                width: 180,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.operate(v, o, r);
                }
            },
            operate2: {
                title: false,
                width: 150,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.operate2(v, o, r);
                }
            },
            recommendRate: {
                name: "recommendRate",
                index: 'recommendRate',
                title: false,
                width: 90,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.recommendRate(v, o, r);
                }
            },
            hot: {
                name: "hot",
                index: 'hot',
                title: false,
                width: 130,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.hot(v,o,r);
                }
            },
            test: {
                name: "test",
                index: 'test',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function(v, o, r) {
                    return Program.Util.formatter.test(v,o,r);
                }
            },
            log_id: {
                name: 'id',
                index: 'id',
                title: false,
                sortable: false,
                hidden: true
            },
            log_addTime:{
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            log_user: {
                name: 'user',
                index: 'user',
                sortable: false,
                title: false,
                width: 150
            },
            log_type: {
                name: 'type',
                index: 'type',
                sortable: false,
                title: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Program.Util.formatter.log_type(v,o, r);
                }
            },
            log_descr: {
                name: "descr",
                index: 'descr',
                title: false,
                width: 450,
                sortable: false
            }
        },
        TABLE_LIBRARY: {
            url: EpgWeb.urlConfig.programList,
            loadBeforeSend: function (xhr, settings) {
                xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                return true;
            },
            rowNum: 40,
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            gridComplete: function () {
                Program.Util.checkPlaying();
            },
            multiselect: false,
            datatype: "local",
            loadtext: '加载中...',
            loadui: "block",
            mtype: "post",
            caption: "节目单列表",
            pager: "#pager",
            colNames: ["奇谱ID", "节目名称", "所属频道", "节目播放状态", "节目状态", "节目类型", "付费状态", "操作", "节目等级",
                "开始时间", "结束时间", "推荐等级", "是否允许进入热门直播", "是否为测试数据", "是否正式流", "更新日期"],
            colModel: ['qipuId', 'pname', 'channelName', 'playStatus' , 'onlineStatus', 'type', 'bossStatus', "operate", "episodeGrade",
                'startPlayTime', 'endPlayTime', "recommendRate", "hot", "test", "formal", 'updateTime']
        },
        TABLE_LIST: {
            url: EpgWeb.urlConfig.programList,
            loadBeforeSend: function (xhr, settings) {
                xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                return true;
            },
            loadComplete: function () {
                var jqGridTarget = $("#list");
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            },
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            multiselect: false,
            mtype: "post",
            datatype: "local",
            height: 450,
            caption: "节目单列表",
            colNames: ["奇谱ID", "节目名称", "开始时间", "结束时间", "节目类型", "付费状态", "更新日期", "操作"],
            colModel: ["qipuId", "pname", "startPlayTime", "endPlayTime", "type", "bossStatus", "updateTime", "operate2"],
            pager: "#pager",
            toolbar: [true, "top"]
        },

        TABLE_LOG: {
            url: EpgWeb.urlConfig.programLog,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/program/loglist");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 50,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "操作时间", "人员", "动作", "备注"],
            colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
            pager: "#log_pager"
        },

        WeekManager: null,
        dateTime: null,
        AUTH_FORCE_CHECK: false,
        AUTH_LOG_DETAIL:false,
        Header:{
            daojuSuggest:["道具渠道号","道具渠道名称","创建时间","创建人"],
            voteSuggest:["投票ID","投票名称","创建时间"],
            puyuSuggest:["条形码","片名","出品方","发行时间","主演 /演唱者","导演","版权方","合同编号","授权起止时间"],
            albumSuggest: ["奇谱ID","显示名称","频道","版权到期时间","是否付费","发布状态"],
            qitanSuggest:["评论ID","评论名称","创建时间"],
            actorSuggest:["人物ID","名称","别名","性别","人物类型","审核状态"],
            playbackSuggest:["节目Id","节目显示名称","频道","发行时间","是否付费","发布状态"]
        },
        EDIT_VALIDATOR: {
            rules: {
                pname:{
                    required:true,

                    maxlength:40
                }
//                qitanId:  {
//                    required:true,
//                    digits: true
//                },
//                subjectUrl:{
//                    url:true
//                }
            },
            messages:{
//                qitanId:{
//                    required:"奇谈id不能为空",
//                    digits:"必须是整数"
//                },
                pname:{
                    required:"节目名称不能为空",
                    maxlength:"节目名称长度不能超过{0}"
                }
            },
            onkeyup: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onkeyup: true
                };

                if (typeof cb.onkeyup == 'function') {
                    cb.onkeyup($element, this);
                } else if (cb.onkeyup) {
                    $element.valid();
                }
            },
            onfocusout: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onfocusout: true
                };

                if (typeof cb.onfocusout == 'function') {
                    cb.onfocusout($element, this);
                } else if (cb.onfocusout) {
                    $element.valid();
                }
            }
        },
        'defaultOperationTabControl': JSON.stringify(
            [
                {'type': 1, 'display_name': '看更多', 'is_enable': '1', 'is_default': '0'},
                {'type': 0, 'display_name': '聊天室', 'is_enable': '1', 'is_default': '1'},
                {'type': 2, 'display_name': '排行榜', 'is_enable': '0', 'is_default': '0'}
            ]
        ),
        'opActivityNums': ["1", "2", "3"],
        PCAT: null
    })


});
define(
    '../entrance_programEdit/Program.Dao',['require','exports','module'],function (require, exports, module) {
        Program.Dao = $.extend({}, EpgWeb.Dao, {

            // 节目添加
            setProgramAddData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programAdd,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/add');
            },
            // 节目修改
            setProgramModifyData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programEdit,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/edit');
            },
            // 节目删除
            deleteProgramData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programDel,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/delete');
            },
            // 紧急检查
            forceCheckProgram: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programForceCheck,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/forceCheck');
            },
            // 获取节目数据列表
            getProgramListByDay: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programList,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/list');
            },

            //检查 导播台
            createDirector:function(data, callback){
                var options = {
                    url: EpgWeb.urlConfig.directorCreateUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/director/create');
            },

            //同步tvmao 节目 start
            syncTVmaoPrograms: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programSyncUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, "/program/syncTVMao");
            },
            //同步tvmao 节目 end

            liveChannelType: function () {
                return this.getDataByName(this.cfgName.liveChannelType)
            },

            liveProgramType: function () {
                return this.getDataByName(this.cfgName.liveProgramType);
            },

            liveType: function () {
                return this.getDataByName(this.cfgName.LiveType);
            },

            episodeGradeType: function () {
                return this.getDataByName(this.cfgName.episodeGradeType);
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },
            recommendRateType:function(){
                return this.getDataByName(this.cfgName.recommendRateType);
            },
            getChannel: function () {
                return this.getDataByName(this.cfgName.getChannel).data;
            },
            targetName: function () {
                return  this.getDataByName(this.cfgName.targetName);
            },
            getProgram: function () {
                var responseData = this.targetName();
                if (responseData == null || responseData.data == null || responseData.data.totalCount == 0) {
                    return null;
                }
                return responseData.data.result[0];
            }
        })

        Program.Dao.cfgName = $.extend({}, EpgWeb.Dao.cfgName,{
            from: "library",
            targetName: "entity",
            puyuData: "puyuData",
            live_temp_other:"live_temp_other",
            category_use:"category_use",
            fatherId: 0,
            id: 0,
            editPic: true,
            categoryArr: null,
            getChannel: "getChannel",
            getLegoChannel: "getLegoChannel",
            liveProgramType: "liveProgramType",
            episodeGradeType: "episodeGradeType",
            getLegoCategory: "getLegoCategory"
        });
    }
);
define('../entrance_programEdit/Program.Util',['require','exports','module'],function (require, exports, module) {
    Program.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            qipuId: function (cellvalue, options, rowObject) {
                var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                return "<a target='_blank' href='" + plusUrl + "'>" + rowObject.qipuId + "</a>";
            },
            pname: function (cellvalue, options, rowObject) {
                if (rowObject.pageUrl != null) {
                    return "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>";
                }
                return cellvalue;
            },
            playStatus: function (cellvalue, options, rowObject) {
                if (cellvalue == null) {
                    return "Not exist ";
                }
                switch (cellvalue) {
                    case -1:
                        return "未设定";
                    case 0:
                        return "未开始";
                    case 1:
                        return "直播中";
                    case 2:
                        return "回看中";
                    case 3:
                        return "回看结束";
                    default :
                        return "Not exist value:" + cellvalue;
                }
                return cellvalue;
            },
            bossStatus: function (cellvalue, options, rowObject) {
                var enumValue = "";
                switch (cellvalue) {
                    case "FREE":
                        enumValue = "免费";
                        break;
                    case "PAIED_NOT_AVAILABLE":
                        enumValue = "<span style='color: red'>付费未划价</span>";
                        break;
                    case "PAIED_AVAILABLE":
                        enumValue = "<span style='color: red'>付费已划价</span>";
                        break;
                    default:
                        break;
                }
                return enumValue;
            },
            type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.liveProgramType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret
            },
            episodeGrade: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.episodeGradeType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                if (ret == "A类一级") {
                    ret = "<span style='color: red'>" + ret + "</span>";
                }
                return ret;
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret;
            },

            channelName: function (cellvalue, options, rowObject) {
                var url = "http://epg.lego.iqiyi.com/epg/channel.html?channelName=" + encodeURIComponent(cellvalue.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
                return "<a target='_blank' href='" + url + "'>" + cellvalue + "</a>";
            },
            onlineStatus: function (cellvalue, options, rowObject) {
                if (cellvalue == 0) {
                    return "删除";
                } else if (cellvalue == 1) {
                    return "启用";
                }
            },
            formal: function (cellvalue, options, rowObject) {
                if (cellvalue == 0) {
                    return "测试";
                } else if (cellvalue == 1) {
                    return "正式";
                }
            },
            operate: function (cellvalue, options, rowObject) {
                var forceCheckStr = "";
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Program.Util.jumpLibraryToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>");
                if (Program.Config.AUTH_FORCE_CHECK && rowObject.channelLiveType == 2) {
                    htmlArr.push("<a href='javascript:;' onclick='Program.Util.checkProgram(" + rowObject.id + ")'>紧急检查</a>");
                }
                htmlArr.push(Program.Util.getBroadcastControl(rowObject));
                htmlArr.push("</br><a href='javascript:;' onclick='Program.Util.delProgram(" + rowObject.id + ")'>删除</a>");
                htmlArr.push("<a href='javascript:;' onclick='Program.Util.openHistory(" + rowObject.id + ")'>详细</a>");
                if (rowObject.directorEnable === 1) {
                    htmlArr.push("<a href='javascript:;' onclick='Program.Util.openDirector(" + rowObject.id + ")'>导播</a>")
                }
                return htmlArr.join("  ")
            },
            operate2: function (cellvalue, options, rowObject) {
                return "<a href='javascript:;' onclick='Program.Util.jumpListToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>  " +
                    Program.Util.getBroadcastControl(rowObject) +
                    "<a href='javascript:;' onclick='Program.Util.delProgram(" + rowObject.id + ")'>删除</a>  " +
                    "<a href='javascript:;' onclick='Program.Util.openHistory(" + rowObject.id + ")'>详细</a>  ";
            },
            /**/
            publishStatus: function (checkValue) {
                if (checkValue == null)
                    return "";
                switch (checkValue) {
                    case 0:
                        return "未发布";
                    case 1:
                        return "已发布";
                    case 2:
                        return "页面下线";
                    case 3:
                        return "页面备用"
                    default:
                        return checkValue + "";
                }
            },
            purchase: function (checkValue) {
                if (checkValue == null)
                    return "";
                switch (checkValue) {
                    case 0:
                    case -100:
                        return "免费";
                    case 1:
                        return "收费";
                    default:
                        return checkValue + ""
                }

            },
            copyrightEndTime: function (checkValue) {
                if (checkValue == null) {
                    return "";
                }
                if (typeof( checkValue ) == "string") {
                    return checkValue;
                }
                if (checkValue <= 0) {
                    return "---";
                } else {
                    var date = new Date();
                    date.setTime(parseInt(checkValue));
                    return  EpgWeb.Util.formatDateTimeFormat(date);
                }
            },
            recommendRate: function (cellvalue, options, rowObject) {
                return Program.Config.RECOMMEND_RATE[cellvalue];
            },
            hot: function (cellvalue, options, rowObject) {
                if (rowObject.channelLiveType != 2) {
                    return "";
                }

                switch (cellvalue) {
                    case 0:
                        return "否";
                    case 1:
                        return "是";
                    default:
                        return "";
                }
            },
            test: function (cellvalue, options, rowObject) {
                if (rowObject.channelLiveType != 2) {
                    return "";
                }
                switch (cellvalue) {
                    case 0:
                        return "否";
                    case 1:
                        return "是";
                    default:
                        return "";
                }
            },
            publish_time: function (cellvalue, options, rowObject) {
                if (cellvalue != "") {
                    return EpgWeb.Util.formatDateTimeFormat(new Date(parseInt(cellvalue) * 1000));
                }
                return "";
            }
        },
        template: {
            daojuSuggest: function (itemArr) {
                return  '<div class="contract-item" >' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width200" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[3] + '</span>' +
                    '</div>'
            },
            voteSuggest: function (itemArr) {

                return '<div class="contract-item" >' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width200" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '</div>';
            },
            albumSuggest: function (itemArr) {
                return   '<div class="contract-item" >' +
                    '<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width60" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>' +
                    '<span class="contract-width80" style="word-break:break-all">' + itemArr[4] + '</span>' +
                    '<span class="contract-width80" style="word-break:break-all">' + itemArr[5] + '</span></div>'
            },
            puyuSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width200" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[2] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[4] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[5] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[6] + '</span>');
                formatArr.push('<span class="contract-width100" style="word-break:break-all">' + itemArr[7] + '</span>');
                formatArr.push('<span class="contract-width200" style="word-break:break-all">' + itemArr[8] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            qitanSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width80" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width250" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width80" style="word-break:break-all">' + itemArr[2] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            actorSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>');
                formatArr.push('<span class="contract-width50" style="word-break:break-all">' + itemArr[3] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[4] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[5] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            playbackSuggest: function (itemArr) {
                return this.albumSuggest(itemArr);
            },
            templateSuggest: function (item) {
                return this.albumSuggest([
                    item["id"],
                    item["label"] ,
                    item["channelName"] ,
                    this.formatter.copyrightEndTime(item.copyrightEndTime),
                    this.formatter.purchase(item.isPurchase),
                    this.formatter.publishStatus(item.pagePublishStatus)
                ])
            }
        },
        setContainer: function ($container) {
            this.$container = $container;
        },
        // 绑定节目编辑事件
        bindEditEvent: function ($container) {

            this._editBindEvent($container);
            this._initEditData($container);

            this._liveTypeLinkage();
            this._initEditEvent();
        },

        _initEditEvent: function () {
            var self = this;
        },
        dispatchLiveChannelType: function (objKey, objValue) {
            return (  parseInt(objKey) < 5 && objValue == "1") ||
                (parseInt(objKey) > 5 && objValue == "2" ) ||
                (  parseInt(objKey) == 5 && objValue == "3" )
        },
        getBroadcastControl: function (rowObj) {
            var hasStream = null != rowObj.channelHasStream && rowObj.channelHasStream == 1;
            if (hasStream) {
                return "<a href='javascript:;' onclick='Program.Util.jumpToBroadcast(" + rowObj.id + "," + rowObj.fatherId + ")'>播控中心</a> ";
            } else {
                return "<a class='disabled'>播控中心</a> ";
            }
        },
        jumpLibraryToEdit: function (entityId, fatherId) {
            var openUrl = "program_edit.html?id=" + entityId + "&from=library&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpListToEdit: function (entityId, fatherId) {
            var openUrl = "program_edit.html?id=" + entityId + "&from=list&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpListToAdd: function (fatherId) {
            var openUrl = "program_edit.html?from=list&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpToBroadcast: function (entityId, fatherId) {
            var openUrl = "broadcast_manager_episode.html?programId=" + entityId + "&id=" + fatherId;
            window.open(openUrl);
        },
        jumpToDirector: function (programQipuId) {
            var openUrl = (auth.dev() ? "" : "http://dbt.lego.iqiyi.com/epg/") + "program_director.html?programQipuId=" + programQipuId
            window.open(openUrl);
        },

        checkProgram: function (entityId) {
            Program.Dao.doAuthData({
                url: '/epg/auth/forceCheck',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有权限!', type: "error"})
                },
                doSuccess: function () {
                    Program.Dao.forceCheckProgram({id: entityId }, function (data) {
                        if (data.code == "A00000") {
                            EpgWeb.Plugin.showTips({ content: data.msg})
                        } else {
                            EpgWeb.Plugin.showTips({ content: data.msg, type: "error"})
                        }
                    })
                }
            })
        },
        checkPlaying: function () {
            var self = this;
            var aimGrid = $("#list");
            var dataOriginl = aimGrid.jqGrid("getData");
            var current = self.formatDateTimeFormat(new Date());
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            $.each(dataOriginl, function (i, element) {
                if (element.startPlayTime <= current && current <= element.endPlayTime) {
                    console.log(" id:" + element.id);
                    aimGrid.setCell(element.id, "startPlayTime", '', {backgroundColor: "#3cb371"}, true);
                    aimGrid.setCell(element.id, "endPlayTime", '', {backgroundColor: "#3cb371"}, true)
                }
            });
        },
        delProgram: function (entityId, fatherId) {
            Program.Dao.doAuthData({
                url: '/epg/program_delete.html',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有删除的权限!', type: "error"})
                },
                doSuccess: function () {
                    SystemDialog.queryConfirm("确认删除？", function (flag) {
                        if (flag === true) {
                            Program.Dao.deleteProgramData({id: entityId }, function (data) {
                                Program.Util.reloadHandler(data);
                            })
                        }
                    })
                }
            })
        },
        openDirector: function (entityId) {
            var dataArr = $("#list").getData();
            var selectEntity = null;
            $.each(dataArr, function (i, element) {
                if (element.id == entityId) {
                    selectEntity = element;
                    return false;
                }
            })
            if (selectEntity == null || selectEntity.directorEnable != 1) {
                return;
            }
            var forbidTime = new Date(selectEntity.endPlayTime.replace(/-/g, "/"))
            forbidTime.setDate(forbidTime.getDate() + 3);
            if (Date.now() > forbidTime.getTime()) {
                SystemDialog.queryAlert("导播台已经被回收!")
                return;
            }
            var newData = {
                programQipuId: selectEntity.qipuId,
                programName: selectEntity.pname,
                startPlayTime: selectEntity.startPlayTime,
                stopPlayTime: selectEntity.endPlayTime,
                source: 1,
                delay: 10,
                outputStreamType: "RESOLUTION_720P"
            };

            Program.Dao.doAuthData({
                url: '/epg/program_director.html',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有导播的权限!', type: "error"})
                },
                doSuccess: function () {
                    Program.Dao.createDirector({"entity": JSON.stringify(newData)}, function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({content: 'director/create 请求异常', type: "error"})
                        } else if (data.code != "A00000") {
                            if (data.data == "-1003") {
                                EpgWeb.Plugin.showTips({content: "第三方接口调用失败", type: "error"})
                            } else {
                                EpgWeb.Plugin.showTips({content: data.msg, type: "error"})
                            }
                        } else {
                            Program.Util.jumpToDirector(newData.programQipuId);
                        }
                    });
                }
            })
        },
        openHistory: function (entityId) {
            Program.Dao.doAuthData({
                url: '/epg/channel_log.html',
                doSuccess: function () {
                    Program.Config.AUTH_LOG_DETAIL = true;
                },
                doFinal: function () {
                    var tableConfig = $.extend(true, {}, Program.Config.TABLE_LOG);
                    tableConfig.width = Program.Config.AUTH_LOG_DETAIL ? 875 : 425
                    var colModel = tableConfig.colModel;
                    var newColModel = [];
                    var colModelConfig = Program.Config.TABLE_COLMODEL_CONFIG;

                    $.each(colModel, function (i, model) {
                        newColModel.push(colModelConfig[model]);
                    });
                    tableConfig.colModel = newColModel;
                    tableConfig.colModel[4].hidden = !Program.Config.AUTH_LOG_DETAIL;
                    $('#logList').jqGrid(tableConfig);
                    $("#programLogDiv").dialog({
                        title: "历史记录",
                        autoOpen: false,
                        width: Program.Config.AUTH_LOG_DETAIL ? 900 : 450,
                        height: 600,
                        modal: true,
                        dialogClass: 'alert',
                        open: function () {
                            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                        }
                    });
                    $("#programLogDiv").dialog("open");
                    $('#logList').jqGrid('setGridParam', {
                        page: 1,
                        datatype: "json",
                        postData: {id: entityId}
                    }).trigger('reloadGrid');
                }
            })
        },
        getValidator: function ($container, config) {
            // var $container = this.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, config);

            return validator;
        },
        //daoju  relation start

        createSign: function (obj, daoju_secret) {
            var self = this;
            var str = '';
            $.each(obj, function (k) {
                str += k + obj[k];
            });
            str += daoju_secret;
            console.log(str);
            return self.hex_sha1(self.utf16to8(str));
        },
        utf16to8: function (str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for (i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
            }
            return out;
        },

        hex_sha1: function (str) {
            var hexcase = 0;
            var chrsz = 8;

            function dosha1(s) {
                return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
            }

            function binb2hex(binarray) {
                var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
                var str = "";
                for (var i = 0; i < binarray.length * 4; i++) {
                    str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
                }
                return str;
            }

            function core_sha1(x, len) {
                x[len >> 5] |= 0x80 << (24 - len % 32);
                x[((len + 64 >> 9) << 4) + 15] = len;

                var w = Array(80);
                var a = 1732584193;
                var b = -271733879;
                var c = -1732584194;
                var d = 271733878;
                var e = -1009589776;

                for (var i = 0; i < x.length; i += 16) {
                    var olda = a;
                    var oldb = b;
                    var oldc = c;
                    var oldd = d;
                    var olde = e;

                    for (var j = 0; j < 80; j++) {
                        if (j < 16) w[j] = x[i + j];
                        else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                        var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                        e = d;
                        d = c;
                        c = rol(b, 30);
                        b = a;
                        a = t;
                    }

                    a = safe_add(a, olda);
                    b = safe_add(b, oldb);
                    c = safe_add(c, oldc);
                    d = safe_add(d, oldd);
                    e = safe_add(e, olde);
                }
                return Array(a, b, c, d, e);

            }

            function sha1_ft(t, b, c, d) {
                if (t < 20) return (b & c) | ((~b) & d);
                if (t < 40) return b ^ c ^ d;
                if (t < 60) return (b & c) | (b & d) | (c & d);
                return b ^ c ^ d;
            }

            function sha1_kt(t) {
                return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
            }

            function safe_add(x, y) {
                var lsw = (x & 0xFFFF) + (y & 0xFFFF);
                var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
                return (msw << 16) | (lsw & 0xFFFF);
            }

            function rol(num, cnt) {
                return (num << cnt) | (num >>> (32 - cnt));
            }

            function str2binb(str) {
                var bin = Array();
                var mask = (1 << chrsz) - 1;
                for (var i = 0; i < str.length * chrsz; i += chrsz)
                    bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
                return bin;
            }

            return dosha1(str);
        },
        reloadHandler: function (data) {
            if (data != null) {
                EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    $("#list").trigger("reloadGrid")
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },
        calculateDate: function (str) {//month 7days yestoday today
            var from_date = "", to_date = "";
            var d = new Date();
            var defaultEnd = this.formatDateTimeFormat(d);
            this.setZeroTime(d);
            if (str == "today") {
                from_date = this.formatDateTimeFormat(d);
                to_date = defaultEnd;
            }
            if (str == "yesterday") {
                d.setDate(d.getDate() - 1);
                from_date = this.formatDateTimeFormat(d);
                this.setDayLastTime(d);
                to_date = this.formatDateTimeFormat(d);
            }

            if (str == "7days") {
                d.setDate(d.getDate() - 6);
                from_date = this.formatDateTimeFormat(d);
                to_date = defaultEnd
            }
            if (str == "month") {
                d.setMonth(d.getMonth() - 1);
                from_date = this.formatDateTimeFormat(d);
                to_date = defaultEnd
            }
            if (str == "absToday") {
                from_date = this.formatDateTimeFormat(d);
                this.setDayLastTime(d);
                to_date = this.formatDateTimeFormat(d);
            }

            if (str == "absToday+") {
                this.setZeroTime(d);
                d.setHours(10);
                from_date = this.formatDateTimeFormat(d);
                d.setDate(d.getDate() + 1);
                to_date = this.formatDateTimeFormat(d);
            }

            this.bindDate("startDate", "endDate", { maxDate: to_date, maxDateTime: new Date(to_date.replace(/-/g, "/")), minDate: from_date, minDateTime: new Date(from_date.replace(/-/g, "/"))})
            $("input[name=startDate]").datetimepicker("setDate", new Date(from_date.replace(/-/g, "/")));
            $("input[name=endDate]").datetimepicker("setDate", new Date(to_date.replace(/-/g, "/")));
        },

        RemoteCheck: (function () {
            var timerId = -1;
            var _handler = null;
            var _startHandler = null;
            var _data = [];

            function startCheck() {
                _startHandler.call(this, _data);
                return setInterval(checkComplete, 16);
            }

            function checkComplete() {
                var allComplete = true;
                $.each(_data, function (index, element) {
                    if (!element.complete) {
                        allComplete = false
                        return true;
                    }
                })
                if (allComplete) {
                    clearInterval(timerId);
                    timerId = -1;
                    console.log("check data over");
                    _handler(_data);
                }
            }

            function doCheck(data, handler, startHandler) {
                if (timerId > 0) {
                    console.log("wait to remote check")
                    return;
                }
                _handler = handler;
                _startHandler = startHandler;
                if (data != null) {
                    if ($.isArray(data)) {
                        _data = data;
                    } else {
                        _data = [data];
                    }
                }
                if (_data == null || _data.length == 0) {
                    handler.call(null)
                    return;
                }

                if (timerId < 0) {
                    timerId = startCheck();
                }
            }

            function clear() {
                _data = [];
            }

            function addToCheck(checkData) {
                _data.push(checkData)
            }

            return{
                clear: clear,
                doCheck: doCheck,
                addToCheck: addToCheck
            }
        })()
    });


});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../entrance_programEdit/Program.Task',['require','exports','module'],function (require, exports, module) {
        Program.Task = $.extend({}, EpgWeb.Task, {
            getLiveProgramType: function (taskName , handler) {
                var self = this;
                if(handler == null ){
                    handler =  function (data) {
                        var selectJDom = $("select[name=liveProgramType]");
                        $("<option value=''>请选择</option>").appendTo(selectJDom);
                        if (data.data != null) {
                            $.each(data.data, function (index, obj) {
                                $("<option>", {
                                    value: obj.key,
                                    html: obj.descr
                                }).appendTo(selectJDom);
                            });
                        }
                        selectJDom.bind("change", function (event) {
                            if (event.currentTarget.value == 1) {
                                $("#sportContainer").show()
                            } else {
                                $("#sportContainer").hide()
                            }
                        })
                    }
                }
                return self.getConfigType(taskName,handler);
            },
            getLegoChannelType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("#channelCateTag");
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.val
                        }).appendTo(selectJDom);
                    });
                })
            },
            getTargetName: function (regName, data) {
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.programList,
                        dataType: "json",
                        data: data
                    }
                }
            },

            getLiveTmpOtherType: function (regName, data) {
                var self = this;
                return self.getConfigType(regName, function (data) {
                    var selectJDom = $("#" + regName);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.val,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            },

            getLiveChannelType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },

            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            },
            getLiveType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=liveType]");
                    var selectChild = $("select[name=liveChannelType]");
                    selectChild.hide();
                    if (data.data == null) {
                        return
                    }
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                    selectJDom.bind("change", function (event) {
                        selectChild.show();
                        selectChild.html("");
                        var appendChildren = [];
                        $.each(Program.Dao.liveChannelType().data, function (index, obj) {
                            if (Program.Util.dispatchLiveChannelType(obj.key, event.currentTarget.value)) {
                                appendChildren.push($("<option>", {
                                    value: obj.key,
                                    html: obj.val
                                }));
                            }
                        });
                        if (appendChildren.length == 0) {
                            selectChild.hide();
                        } else {
                            appendChildren = [$("<option value=''>请选择</option>")].concat(appendChildren)
                        }
                        $.each(appendChildren, function (i, element) {
                            element.appendTo(selectChild);
                        })
                    })
                })
            },
            sendTask: function (modelData, sendImageDatas) {
                return {
                    regName: null,
                    options: {
                        type: "post",
                        dataType: "json",
                        data: {"data": JSON.stringify(modelData), "imageDatas": sendImageDatas == null ? null : JSON.stringify(sendImageDatas) },
                        success: function (data) {
                            //   callback
                        },
                        error: function (data) {

                        }
                    }
                }
            },

            getGradeType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=episodeGrade]");
                    $("<option>", {value: "", html: "请选择"}).appendTo(selectJDom);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            },
            getRecommendType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=recommend_rate]");
                    $("<option>", {value: "", html: "请选择"}).appendTo(selectJDom);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            }


        })
    }
);
define(
    '../entrance_programEdit/Program.Edit',['require','exports','module'],function (require, exports, module) {
        Program.Edit = function (options) {
            this.dao = Program.Dao;
            this.task = Program.Task;
            this.config = Program.Config;
            this.options = options || {};
        };
        Com.inherits(Program.Edit, function (options) {
        }).extend({
            init: function () {
                var self = this;
                self.$container = $(".video-edit-form");
                Program.Util.setContainer(self.$container);
                var taskArr = [];
                var param_id = Com.url.getParameter("id");
                var param_from = Com.url.getParameter("from");
                if (param_id != null) {
                    self.dao.cfgName.id = Number(param_id);
                    taskArr.push(self.task.getTargetName(self.dao.cfgName.targetName, {id: param_id}));
                }
                if (param_from != null) {
                    self.dao.cfgName.from = param_from;
                }
                self.remoteCheck = Program.Util.RemoteCheck;
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType, function (data) {
                }));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                taskArr.push(self.task.getLegoChannelType(self.dao.cfgName.category_use));
                taskArr.push(self.task.getLiveTmpOtherType(self.dao.cfgName.live_temp_other));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: fatherId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    $('div[name=multiAddDiv]').addndel({
                        rowClass: 'control-group'
                    })
                    Program.FileUpload.doInit($('#AlbumEditScreenCorp'))
                    self.initEditForm();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initEditForm: function () {
                $("form[role=form]").submit(function () {
                    return false;
                })
                var self = this;

                self.initDefault();
                if (self.dao.cfgName.id > 0) {
                    self.initByProgramData();
                } else {
                    self.initByChannelData()
                }
                self.initDialog();
                self.initEditPicZone();
                self.initSuggest();
                self.initRelationDataArea()
                self.bindEditEvent();
                self.bindValidate();
            },
            submit: function () {
                console.log("wait to do")
            },
            prepareModel: function () {
                var self = this;
                var entity = {};
                var programEntity = self.dao.getProgram();
                if (programEntity != null) {
                    entity.id = programEntity.id;
                    entity.updateTime = programEntity.updateTime;
                    entity.fatherId = programEntity.fatherId;
                } else {
                    entity.fatherId = $("#fatherId").val();
                }
                entity.pname = $("#pname").val();
                entity.startPlayTime = $("#startPlayTime").val();
                entity.endPlayTime = $("#endPlayTime").val();
                entity.streamStartPlayTime = $("#streamStartPlayTime").val();
                entity.streamEndPlayTime = $("#streamEndPlayTime").val();
                entity.qitanId = $("#qitanId").val();
                entity.waterMarkFlag = $('input:radio[name=waterMarkFlag]:checked').val() == 1 ? true : false;
                entity.subscribe = $("input[name=subscribe]:checked").val();
                entity.allowPopups = $('input:radio[name=dan_mu]:checked').val() == 1 ? true : false;
                entity.freeStatus = $('input:radio[name=freeStatus]:checked').val() == 1 ? true : false;
                entity.vipType = $('select[name=vipType]').val();
                entity.weiboTopic = $("input[name=weiboTopic]").val()
                entity.leftChannel = "";
                entity.audioChannel = "";
                entity.videoPieceLength = 0;
                entity.rightChannel = "";
                entity.description = $("#description").val();
                entity.type = $("#type").val();
                entity.orderBy = 1000;
                entity.allowComment = $("input:radio[name=qitanMarkFlag]:checked").val() == 1 ? true : false;
                entity.logoUrl = "";
                entity.relationList = self.prepareRelation(entity.type);
                entity.qiyiProduct = $("input:radio[name=qiyiProduct]:checked").val() == 1 ? true : false;
                entity.qiyiExclusive = $("input:radio[name=qiyiExclusive]:checked").val() == 1 ? true : false;
                entity.barCode = "";
                entity.episodeGrade = parseInt($("select[name=episodeGrade]").val());
                if (isNaN(entity.episodeGrade)) {
                    entity.episodeGrade = 0;
                }
                entity.daojuEnable = $('input:radio[name=daojuFlag]:checked').val();
                entity.daojuId = $('#daojuId').data('id');
                entity.daojuName = $('#daojuId').val();
                entity.userName = $('header a.name').html();
                entity.chatEnable = $('input:radio[name=chat_enable]:checked').val()
                entity.chatDisplay = $('input:radio[name=chat_display]:checked').val()
                entity.chatRoomId = 0;
                entity.category = "[]";
                entity.uid = Number($("input[name=hidden_uid]").val());
                entity.recommendRate = parseInt($("select[name=recommendRate]").val())
                entity.hot = parseInt($('input:radio[name=hot]:checked').val())
                entity.test = parseInt($('input:radio[name=test]:checked').val())
                if ($("input[name=recommendRemark]").val().length > 0) {
                    entity.recommendRemark = $("input[name=recommendRemark]").val();
                }
                if ($.trim($("input[name=subjectUrl]").val()).length > 0) {
                    entity.subjectUrl = $.trim($("input[name=subjectUrl]").val());
                }
                entity.projectType = $("select[name=project_type_select]").val();
                var channelEntity = self.dao.getChannel();
                if (channelEntity == null) {
                    return
                }
                if (channelEntity.liveType == 2) {
                    entity.categoryCheck = self.makeUpCategory();
                    entity.category = JSON.stringify(entity.categoryCheck);
                }
                return entity;
            },
            prepareRelation: function (entityType) {
                var self = this;
                var relationList = [];
                var channelEntity = self.dao.getChannel();
                if (channelEntity == null) {
                    return
                }
                var _fatherId = channelEntity.id;
                relationList = relationList.concat(self.prepareMultipleItem('#ajaxSuggest', _fatherId, 1, true));
                var item = [];
                if (entityType == 1) {
                    $("input[name=base_3_team]").each(function (index, target) {
                        var $target = $(target)
                        var $targetValue = $target.val();
                        if ($.trim($targetValue).length > 0) {
                            var $scoreValue = $target.parent().find("input[name=base_3_score]").val();
                            if ($.trim($scoreValue).length == 0 || isNaN($scoreValue)) {
                                $scoreValue = 0;
                            } else {
                                $scoreValue = parseInt($scoreValue);
                            }
                            relationList.push({fatherId: _fatherId, "key": $scoreValue, type: 3, "value": $targetValue })
                        }
                    })
                }
                item = self.prepareSingleItem("input[name=playbackSuggest]", _fatherId, 7, true);
                if (item != null) {
                    relationList.push(item);
                }

                item = self.prepareSingleItem("#votePK", _fatherId, 106, true, true);
                if (item != null) {
                    relationList.push(item);
                }
                item = self.prepareSingleItem("#voteRank", _fatherId, 107, true, true);
                if (item != null) {
                    relationList.push(item);
                }

                var keySelect = $("select[name=frontSuggestType]").val();
                if (keySelect == "simple-video") {
                    relationList = relationList.concat(self.prepareMultipleItem('#appendFront_' + keySelect, _fatherId, 5, true));
                } else {
                    item = self.prepareSingleItem('#appendFront_' + keySelect, _fatherId, 5)
                    if (item != null) {
                        relationList.push(item);
                    }
                }
                keySelect = $("select[name=endSuggestType]").val();
                if (keySelect == "simple-video") {
                    relationList = relationList.concat(self.prepareMultipleItem('#appendEnd_' + keySelect, _fatherId, 6, true));
                } else {
                    item = self.prepareSingleItem('#appendEnd_' + keySelect, _fatherId, 6)
                    if (item != null) {
                        relationList.push(item);
                    }
                }
                if (2 == channelEntity.liveType) {
                    var live_tmp_other = $("#live_temp_other").val();
                    if (live_tmp_other.length > 0) {
                        relationList.push({fatherId: _fatherId, key: 0, type: 201, value: live_tmp_other });
                    }
                    // relate passport id
                    var passportId = {uid: $.trim($("input[name=uid_hidden]").val()), nickname: $.trim($("input[name=nickname_hidden]").val())};
                    if (passportId.uid.length > 0 && passportId.nickname.length > 0) {
                        var type301 = {fatherId: _fatherId, key: 0, type: 301, value: passportId.uid };
                        var type302 = {fatherId: _fatherId, key: 0, type: 302, value: passportId.nickname };
                        var dataValid = false;
                        if ($("select[name=passport_select]").val() == "option_uid") {
                            type301.key = 1;
                            dataValid = $.trim($("input[name=passport_uid]").val()) == type301.value;
                            console.log(" passport id 验证失效 " + JSON.stringify(type301) + "  ; " + $.trim($("input[name=passport_uid]").val()));
                        } else if ($("select[name=passport_select]").val() == "option_nickname") {
                            type302.key = 1;
                            dataValid = $.trim($("input[name=passport_nickname]").val()) == type302.value;
                            console.log(" passport id 验证失效 " + JSON.stringify(type302) + "  ; " + $.trim($("input[name=passport_nickname]").val()));
                        }
                        if (dataValid) {
                            relationList.push(type301);
                            relationList.push(type302);
                        } else {
                            console.log(" passport id 验证失效 " + JSON.stringify(type301) + ";" + JSON.stringify(type302));
                        }
                    }
                }
                return relationList;
            },
            prepareSingleItem: function (regName, fatherId, type, filterZero, filterEmpty) {
                var singleValue = $.trim($(regName).suggest("getValue"));
                var isNum = EpgWeb.Plugin.Validate.checkNum(singleValue)
                if (!isNum) {
                    return null;
                }
                if (filterEmpty) {
                    if ($.trim($(regName).val()) == "") {
                        return null;
                    }
                }
                if (filterZero) {
                    if (singleValue === '0') {
                        return null;
                    }
                }
                return {fatherId: fatherId, "key": parseInt(singleValue), type: type, "value": "" }
            },

            prepareMultipleItem: function (regName, fatherId, type, needValue) {
                var relationList = [];
                needValue = needValue ? true : false;
                var items = $(regName).suggest("getItems");
                $.each(items, function (index, element) {
                    if (element.id != null) {
                        relationList.push({fatherId: fatherId, "key": element.id, type: type, "value": needValue ? element.label : "" });
                    }
                });
                return relationList
            },
            bindEditEvent: function () {
                var self = this;
                $("#qitanId").focusout(function () {
                    var flag = EpgWeb.Plugin.baseCheck({value: $("#qitanId").val(), error: "请输入整数", handler: function (msg) {
                        var helpHint = $("span[for=qitanId]");
                        helpHint.html("请输入整数");
                    }, type: "number"})
                    if (!flag) {
                        return;
                    }
                })

                if (self.dao.cfgName.id > 0) {
                    self.editPic(false);
                    $(".header button").bind("click", function (event) {
                        self.editPic(true);
                    });
                }
                //leftWordsCount
                Program.Util.limitWordCount($("#description"), 200);
                Program.Util.limitWordCount($("#recommendRemark"), 10);

                $("select[name$=SuggestType]").bind("change", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var selectedValue = $curTarget.val();
                    console.log("selectedValue")
                    $curTarget.parent().find("span input").parent().hide();
                    $curTarget.parent().find("span input[name$=_" + selectedValue + "]").parent().show();
                })
                $("select[name=frontSuggestType]").change();
                $("select[name=endSuggestType]").change();
                $("select[name$=SuggestType]").parent().find("span input").show();

                $("input[name=use_puyu_radio]").bind("click", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var puyuDiv = $("#puyuDiv");
                    if ($curTarget.val() == 1) {
                        puyuDiv.show();
                    } else {
                        puyuDiv.hide();
                        puyuDiv.find("input[type=text]").val("");
                    }
                })

                $("select[name=channelCateTag]").bind("change", function (event) {
                    $("#secTagDiv").show();
                    $("#secTagZone").html("数据加载中....");
                    $("#thirdTagDiv").hide();
                    $("#thirdTagZone").html("");
                    var $curTarget = $(event.currentTarget)
                    var selectedValue = $curTarget.val();
                    self.queryForLvOne({channel_id: parseInt(selectedValue), liveDisplay: 1, liveUsed: 1});
                });

                $("input[name=chat_enable]").bind("click", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var chatShowDiv = $("#chatShowDiv");
                    var chatRoomId = $("label[name=chatRoomId]");
                    var daojuFlag = $("input[name=daojuFlag]");
                    if ($curTarget.val() == 1) {
                        chatShowDiv.show();
                        chatRoomId.show();
                        daojuFlag.removeAttr("disabled");
                    } else {
                        chatShowDiv.hide();
                        chatRoomId.hide();
                        $('input[name=daojuFlag][value="0"]').prop("checked", true);
                        $("input[name=daojuFlag]:checked").click();
                        daojuFlag.attr("disabled", "disabled");
                    }
                });

                $("input[name=chat_enable]:checked").click();

                $("input[name=daojuFlag]").bind("click", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var daoju = $("#daoju");
                    var daojuFlag = $("input[name=daojuFlag]");
                    if ($curTarget.val() == 1) {
                        daoju.show();
                        var daojuId = $('#daojuId').data('id');
                        if (daojuId && daojuId !== '') {
                            $("input[name=daoju]").attr("disabled", "disabled");
                            $('#daojuTip').html("渠道号: " + daojuId);
                        }
                        $("label[name=remind_item]").show();
                    } else {
                        daoju.hide();
                        $("label[name=remind_item]").hide();
                    }
                });
                $("input[name=daojuFlag]:checked").click();

                $('#daojuId').bind('input propertychange', function () {
                    if ($(this).val().length == 0) {
                        $('#daojuTip').html("");
                    }
                });

                $("select[name=passport_select]").bind("change", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var selectedValue = $curTarget.val();
                    if (selectedValue == "option_uid") {
                        $("input[name=passport_nickname]").val("");
                        $("input[name=passport_nickname]").parent().find("span").html("");
                        $("#passport_uid_div").css("display", "inline")
                        $("#passport_nickname_div").hide();
                    } else if (selectedValue == "option_nickname") {
                        $("input[name=passport_uid]").val("");
                        $("input[name=passport_uid]").parent().find("span").html("");
                        $("#passport_uid_div").hide();
                        $("#passport_nickname_div").css("display", "inline")
                    }
                })

                $("select[name=project_type_select]").bind("change", function (event) {
                    var $curTarget = $(event.currentTarget)
                    var selectedValue = $curTarget.val();
                    if (selectedValue == "type_sale") {
                        $("input[name=hot][value='0']").prop("checked", true);
                    } else if (selectedValue == "type_nosale") {
                        $("input[name=hot][value='1']").prop("checked", true);
                    }
                })

                var channelEntity = self.dao.getChannel();
                if (channelEntity != null && channelEntity.liveType == 2) {
                    $("#channelCateTag").change();
                    $("select[name=passport_select]").change();
                }


                $("select[name=episodeGrade]").bind("change", function (event) {
                    var $curTarget = $(event.currentTarget);
                    var selectedValue = $curTarget.val();
                    self.updateRecommendRateWithEpisodeGrade(selectedValue);
                });
            },

            updateRecommendRateWithEpisodeGrade: function (val) {
                var recommendVal = 0;
                if (val == '') {
                    recommendVal = 0;
                } else {
                    recommendVal = 3 - parseInt(val) % 10 + 1;
                }
                $("select[name=recommendRate]").val(recommendVal);
            },
            editPic: function (flag) {
                var self = this;
                if (flag) {
                    $(".header button").hide();
                    $(".results button").removeAttr("disabled");
                    $(".operation").removeClass("disabled");
                    $(".uploadButton").removeAttr("disabled");
                    $(".button-manual").removeAttr("disabled");
                    self.dao.cfgName.editPic = true;
                } else {
                    $(".header button").show();
                    $(".header button").removeAttr("disabled");
                    $(".results button").prop("disabled", "disabled");
                    $(".operation").addClass("disabled");
                    $(".uploadButton").prop("disabled", "disabled");
                    $(".button-manual").prop("disabled", "disabled");
                    self.dao.cfgName.editPic = false;
                }
            },
            initDefault: function () {
                $("#qitanId").val("");
                $("input[name=_simple-video]").val("");
                $("input[name=_album]").val("");
                $("input[name=_playlist]").val("");
                $("input[name=use_puyu_radio]").removeAttr("checked");
                $("input[name=bType]").removeAttr("checked");
                $("input[name=bType]").attr("disabled", "disabled");
                $("#puyuShowDiv").hide();
                $("input[name=use_puyu_radio]").removeAttr("checked");
                $("#channelCateTag").val(7);
            },
            initLiveProgramType: function () {
                var self = this;
                var channelEntity = self.dao.getChannel();
                if (channelEntity == null) {
                    return
                }
                var result = self.dao.liveProgramType();
                var selectJDom = $("select[name=liveProgramType]");
                var createDataArr = [];
                $.each(result.data, function (index, obj) {
                    switch (channelEntity.liveType) {
                        case 1:
                            if (obj.key == 6) {
                                createDataArr.push(obj);
                            }
                            break;
                        case 2:
                            if (obj.key < 6) {
                                createDataArr.push(obj);
                            }
                            break;
                        case 3:
                            if (obj.key == 7) {
                                createDataArr.push(obj);
                            }
                            break;
                    }
                });
                $.each(createDataArr, function (index, obj) {
                    $("<option>", {
                        value: obj.key,
                        html: obj.descr
                    }).appendTo(selectJDom);
                });
                selectJDom.bind("change", function (event) {
                    if (event.currentTarget.value == 1) {
                        $("#sportContainer").show()
                    } else {
                        $("#sportContainer").hide()
                    }
                })
            },

            initByProgramData: function () {
                var self = this;
                var programEntity = self.dao.getProgram();
                if (programEntity.category != null) {
                    programEntity.categoryArr = JSON.parse(programEntity.category);
                }

                $("#fatherId").val(programEntity.fatherId);
                self.appendChannelList($("#fatherId").val());
                $("#endPlayTime").val(programEntity.endPlayTime);
                $("#endPlayTime").attr("readonly", "readonly");
                if (programEntity.carouselEpisode > 0) {
                    $("label[name=carouselEpisode]").html(programEntity.carouselEpisode);
                }
                $("#startPlayTime").attr("readonly", "readonly");
                $("#qitanId").val(programEntity.qitanId);
                $("select[name=liveProgramType]").val(programEntity.type);
                if (programEntity.episodeGrade > 0) {
                    $("select[name=episodeGrade]").val(programEntity.episodeGrade);
                }
                if (programEntity.type != 1) {
                    $("#sportContainer").hide();
                }
                $("#pname").val(programEntity.pname);
                $("input[name=weiboTopic]").val(programEntity.weiboTopic);
                $("input[name=leftChannel]").val(programEntity.leftChannel);
                $("input[name=audioChannel]").val(programEntity.audioChannel);
                $("input[name=rightChannel]").val(programEntity.rightChannel);

                $("select[name=recommendRate]").val(programEntity.recommendRate);
                $("select[name=project_type_select]").val(programEntity.projectType || "");
                $("input[name=recommendRemark]").val(programEntity.recommendRemark || "");
                $("input[name=subjectUrl]").val(programEntity.subjectUrl || "");

                $("#description").val(programEntity.description);
                $("#logoUrl").val(programEntity.logoUrl);
                $("#input[name=orderLevel]").val(programEntity.orderBy);
                $("input[name=waterMarkFlag][value='" + programEntity.waterMarkFlag + "']").prop("checked", true);
                $("input[name=subscribe][value='" + programEntity.subscribe + "']").prop("checked", true);
                $("input[name=dan_mu][value='" + programEntity.allowPopups + "']").prop("checked", true);
                $("input[name=qitanMarkFlag][value='" + programEntity.allowComment + "']").prop("checked", true);
                $("input[name=freeStatus][value='" + (programEntity.freeStatus ? 1 : 0) + "']").prop("checked", true)
                $("select[name=vipType]").val(programEntity.vipType);
                $("input[name=qiyiProduct][value='" + (programEntity.qiyiProduct || 0) + "']").prop("checked", true);
                $("input[name=qiyiExclusive][value='" + (programEntity.qiyiExclusive || 0) + "']").prop("checked", true)
                self.fillDataByChannelData();
                self.bindSubmitHandler("edit");
                $("#puyuDiv").hide();
                $("input[name=use_puyu_radio][value='0']").prop("checked", true);
                if (programEntity.barCode != null && programEntity.puyuData != null) {
                    if (self.fillPuYuField(programEntity.puyuData)) {
                        $("input[name=puyu_barCode]").val(programEntity.barCode);
                        $("input[name=suggest_barCode]").val(programEntity.barCode);
                        $("input[name=use_puyu_radio][value='" + 1 + "']").prop("checked", true);
                        $("#puyuDiv").show();
                    }
                }
                if (programEntity.chatRoomId > 0) {
                    $("label[name=chatRoomId]").html("聊天室ID：" + programEntity.chatRoomId);
                }
                $('input[name=chat_enable][value=' + programEntity.chatEnable + ']').prop("checked", true);
                $('input[name=chat_display][value=' + programEntity.chatDisplay + ']').prop("checked", true);
                if (programEntity.chatRoomId > 0 && programEntity.chatEnable == 0) {
                    $("input[name=chat_enable]").attr("disabled", "disabled");
                    $("input[name=chat_display]").attr("disabled", "disabled");
                }

                $('input[name=daojuFlag][value=' + programEntity.daojuEnable + ']').prop("checked", true);
                $('#daojuId').val(programEntity.daojuName);
                $('#daojuId').data("id", programEntity.daojuId);
                if (programEntity.daojuEnable === 1 && typeof programEntity.daojuId !== 'undefined' && programEntity.daojuId !== '') {
                    $('#daojuTip').html("渠道号: " + programEntity.daojuId);
                    $('#daojuId').attr("disabled", "disabled");
                }

                // init puyu relation end;

                var channelEntity = self.dao.getChannel();
                if (channelEntity == null) {
                    return
                }
                if (channelEntity.liveType != 3) {
                    $("#bTypeDiv").hide();
                } else {
                    $("#bTypeDiv").show();
                    $("input[name=bType][value=" + programEntity.live + "]").prop("checked", true);
                }

                if (channelEntity.liveType == 2) {
                    if (programEntity.categoryCheck != null) {
                        $.each(programEntity.categoryCheck, function (i, element) {
                            if (element.level == 1) {
                                $("#channelCateTag").val(element.id);
                                return false;
                            }
                        })
                    }
                    $("#endPlayTime").removeAttr("readonly");
                    $("#startPlayTime").removeAttr("readonly");
                    Program.Util.bindDate("startPlayTime", "endPlayTime", { maxDate: programEntity.endPlayTime, maxDateTime: new Date(programEntity.endPlayTime.replace(/-/g, "/")), minDate: programEntity.startPlayTime, minDateTime: new Date(programEntity.startPlayTime.replace(/-/g, "/"))});
                    $("input[name=startPlayTime]").datetimepicker("setDate", new Date(programEntity.startPlayTime.replace(/-/g, "/")));
                    $("input[name=endPlayTime]").datetimepicker("setDate", new Date(programEntity.endPlayTime.replace(/-/g, "/")));

                    Program.Util.bindDate("streamStartPlayTime", "streamEndPlayTime", { maxDate: programEntity.streamEndPlayTime, maxDateTime: new Date(programEntity.streamEndPlayTime.replace(/-/g, "/")), minDate: programEntity.streamStartPlayTime, minDateTime: new Date(programEntity.streamStartPlayTime.replace(/-/g, "/"))});
                    $("input[name=streamStartPlayTime]").datetimepicker("setDate", new Date(programEntity.streamStartPlayTime.replace(/-/g, "/")));
                    $("input[name=streamEndPlayTime]").datetimepicker("setDate", new Date(programEntity.streamEndPlayTime.replace(/-/g, "/")));

                    $("input[name=freeStatus]").prop("disabled", "disabled");
                    $("#playbackSuggest").val(0);
                } else if (channelEntity.liveType == 1) {
                    $("#pname").prop("disabled", "disabled");
                    $("input[name=freeStatus][value='" + 1 + "']").prop("checked", true);
                    $("input[name=freeStatus][value='" + 1 + "']").parent().parent().hide();
                } else if (channelEntity.liveType == 3) {
                    $("label[name=carouselEpisode]").show();
                    $("input[name=freeStatus]").prop("disabled", "disabled");
                    if (new Date(programEntity.startPlayTime.replace(/-/g, "/")).getTime() - new Date().getTime() > 30 * 60 * 1000) {
                        $("#endPlayTime").removeAttr("readonly");
                        $("#startPlayTime").removeAttr("readonly");
                        Program.Util.bindDate("startPlayTime", "endPlayTime", { maxDate: programEntity.endPlayTime, maxDateTime: new Date(programEntity.endPlayTime.replace(/-/g, "/")), minDate: programEntity.startPlayTime, minDateTime: new Date(programEntity.startPlayTime.replace(/-/g, "/"))});
                        $("input[name=startPlayTime]").datetimepicker("setDate", new Date(programEntity.startPlayTime.replace(/-/g, "/")));
                        $("input[name=endPlayTime]").datetimepicker("setDate", new Date(programEntity.endPlayTime.replace(/-/g, "/")));

                        Program.Util.bindDate("streamStartPlayTime", "streamEndPlayTime", { maxDate: programEntity.streamEndPlayTime, maxDateTime: new Date(programEntity.streamEndPlayTime.replace(/-/g, "/")), minDate: programEntity.streamStartPlayTime, minDateTime: new Date(programEntity.streamStartPlayTime.replace(/-/g, "/"))});
                        $("input[name=streamStartPlayTime]").datetimepicker("setDate", new Date(programEntity.streamStartPlayTime.replace(/-/g, "/")));
                        $("input[name=streamEndPlayTime]").datetimepicker("setDate", new Date(programEntity.streamEndPlayTime.replace(/-/g, "/")));
                    } else {
                        $("#startPlayTimeTip").html('该节目已结束，时间不允许修改');
                    }
                }

                $('input[name=hot][value=' + programEntity.hot + ']').prop("checked", true);
                $('input[name=test][value=' + programEntity.test + ']').prop("checked", true);

                if (channelEntity.liveType != 2) {
                    $("#hotDiv").hide();
                    $("#testDiv").hide();
                }
            },
            bindSubmitHandler: function (type) {
                var self = this;
                self.$validator = Program.Util.getValidator(self.$container, self.config.EDIT_VALIDATOR);
                var submitButton = $("button[type=submit]");
                submitButton.bind("click", function () {
                    if (!self.$validator.form()) {
                        return false;
                    }
                    console.log("ready to submit " + type + "Data");
                    self.submitHandler(type);
                    return false;
                });
            },
            fillDataByChannelData: function () {
                var self = this;
                var element = self.dao.getChannel();
                if (element == null || element.allowPopups != 1) {
                    $("input[name=dan_mu]").attr("disabled", "disabled")
                    $("label[name=danmuHint]").css("display", "inline");
                }
                if (element != null && element.liveType == 2) {
                    $("#channelCateTagDiv").show();
                    $("#secTagDiv").show();
                    $("#thirdTagDiv").show();
                    $("#puyuShowDiv").show();
                    $("#episodeGradeDiv").show();
                    $("span[name=playbackForce]").show();
                    $("label[name=playbackHint]").show();
                    $("#liveTmpDiv").show();
                    $("#projectDiv").show();
                }
            },
            initByChannelData: function () {
                var self = this;
                var element = self.dao.getChannel();
                if (self.dao.cfgName.id == 0) {
                    if (element != null) {
                        $("#fatherId").val(Com.url.getParameter("fatherId"));
                        self.appendChannelList($("#fatherId").val(), true);
                    } else {
                        self.appendChannelList();
                    }
                }
                Program.Util.bindDate("startPlayTime", "endPlayTime");
                Program.Util.bindDate("streamStartPlayTime", "streamEndPlayTime");
                self.bindSubmitHandler("save");
                self.fillDataByChannelData();
            },
            appendChannelList: function (fatherId, newProgram) {
                var self = this;
                var element = self.dao.getChannel()
                if (element != null) {
                    var selectJDom = $("#selectedChannelName");
                    selectJDom.val(element.name);
                    selectJDom.attr("readonly", "readonly");
                    $("input[name=orderLevel]").val(element.orderBy);
                    $('#qitanId').val(element.qitanId);
                    $('#subjectUrlDiv').hide();
                    if (element.liveType == 2) {
                        $('#subjectUrlDiv').show();
                    }
                    $("input[name=subjectUrl]").val(element.subjectUrl || "");

                }
                if (newProgram) {
                    $("input[name=dan_mu][value='" + element.allowPopups + "']").prop("checked", true);
                    $("input[name=qitanMarkFlag][value='" + element.shouldDisplay + "']").prop("checked", true);
                }
            },

            initRelationDataArea: function () {
                var self = this;
                if (self.dao.cfgName.id == 0) {
                    return;
                }
                var programEntity = self.dao.getProgram();
                if (programEntity == null) {
                    self.initByNull();
                    return;
                }
                self.fillRelationData(programEntity.relationList);
            },

            initByNull: function () {
                var self = this;
                EpgWeb.Plugin.showTips({content: "not such data", type: "error"});
                self.dao.cfgName.id = 0;
                $("input[name=dan_mu]").attr("disabled", "disabled")
                $("form[role=form]").submit(function () {
                    EpgWeb.Plugin.showTips({content: "非法数据", type: "error"});
                    return false;
                })
            },

            fillPuYuField: function (puyuData) {
                if (puyuData == null) {
                    return false;
                }
                var self = this;
                try {
                    var puyuJson = null;
                    if (typeof(puyuData ) == "string") {
                        puyuJson = JSON.parse(puyuData);
                    } else {
                        puyuJson = puyuData;
                    }
                    var dataArr = puyuJson.cprContents;
                    var element = dataArr.length > 0 ? dataArr[0] : null;
                    return self.fillPuYuOnClick(element);
                } catch (exception) {
                    console.log(" exception " + exception);
                    return false;
                }
            },

            fillPuYuOnClick: function (puyuData) {
                if (typeof(puyuData) == "string") {
                    console.log("wait to do");
                    return false;
                }
                var element = puyuData;
                if (!element.hasOwnProperty("contractNumber")
                    || !element.hasOwnProperty("videoName")
                    || !element.hasOwnProperty("startTime")
                    || !element.hasOwnProperty("endTime")
                    || !element.hasOwnProperty("cprName")
                    ) {
                    console.log("[fillPuYuOnClick] fail element :" + JSON.stringify(element))
                    return false;
                }
                $("input[name=puyu_contractNumber]").val(element.contractNumber);
                $("input[name=puyu_videoName]").val(element.videoName);
                $("input[name=puyu_startTime]").val(element.startTime);
                $("input[name=puyu_endTime]").val(element.endTime)
                $("input[name=puyu_cprName]").val(element.cprName);
                return true;
            },
            initSuggest: function () {

                var formElement = this;
                var qitanSuggest = {id: "qitanId", options: {
                    source: EpgWeb.urlConfig.redirect,
                    parseValue: function () {
                        return [];
                    },
                    multiple: false,
                    select: function (event, object) {
                        this.value = object.item.id + "";
                        return false;
                    },

                    process: function (json) {
                        var ret = [],
                            self = this,
                            options = self.options,
                            itemData = null;
                        var data = null;
                        if (json == null) {
                            return [];
                        }
                        if (json.code === "A00000") {
                            data = $.isArray(json) ? json : json.data;
                        }
                        if (!data || !data.ids) {
                            return [];
                        }
                        $.map(data.ids, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["resourceId"];
                            itemData[options.labelKey] = item["name"];
                            itemData["addDate"] = item["addDate"]
                            ret.push(itemData);
                        });
                        return ret;
                    },
                    method: "post",
                    getParam: function (owner, term) {
                        var requestData = {url: EpgWeb.Constant.thirdUrl_qitan_url, type: "get", params: {name: this.element.val(), resource_type: 1, page_size: 10}};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },

                    template: function (item) {
                        return Program.Util.template.qitanSuggest([item["id"], item["label"], item["addDate"] ])
                    },
                    header: Program.Util.template.qitanSuggest(Program.Config.Header.qitanSuggest)
                }}
                var actorSuggest = {id: "ajaxSuggest", options: {
                    source: EpgWeb.urlConfig.redirect,
                    parseValue: function () {
                        var self = this;
                        var val = this.element.val(),
                            ret = [],
                            items = null,
                            itemData = null,
                            options = self.options;

                        if (val) {
                            items = val.split(';');
                            $.each(
                                items, function (i, item) {
                                    item = item.split(',');
                                    itemData = {};
                                    itemData[options.labelKey] = item[1];
                                    itemData[options.valueKey] = item[0];
                                    ret.push(itemData);
                                }
                            );
                        }
                        this._value('');
                        return ret;
                    },
                    process: function (json) {
                        var ret = [],
                            self = this,
                            options = self.options,
                            itemData = null;
                        var data = null;
                        if (json == null) {
                            return [];
                        }
                        if (json.code === "A00000") {
                            data = $.isArray(json) ? json : json.data;
                        }
                        if (!data) {
                            return [];
                        }
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["qipuId"];
                            itemData[options.labelKey] = item["properName"];
                            itemData["typeName"] = item["typeName"]
                            itemData["showId"] = item["id"];
                            itemData["gender"] = item.gender == null ? "" : item.gender == 0 ? "男" : "女";
                            itemData["auditStatus"] = item["auditStatus"] == 1 ? "审核通过" : "未审核";
                            itemData["careerName"] = item["careerName"];
                            ret.push(itemData);
                        });
                        return ret;
                    },
                    method: "post",
                    getParam: function (owner, term) {
                        var requestData = {url: EpgWeb.Constant.thirdUrl_audit_people, type: "get", params: {word: this.element.val()}};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },

                    template: function (item) {
                        var formatArr = [];
                        formatArr.push(item.showId);
                        formatArr.push(item["label"]);
                        formatArr.push(item["careerName"]);
                        formatArr.push(item.gender);
                        formatArr.push(item.typeName);
                        formatArr.push(item.auditStatus);
                        return Program.Util.template.actorSuggest(formatArr)
                    },
                    header: Program.Util.template.actorSuggest(Program.Config.Header.actorSuggest)
                }};

                var playbackSuggest = {
                    id: "playbackSuggest",
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        select: function (event, object) {
                            this.value = object.item.id + "";
                            return false;
                        },
                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData[self._displayKey] = item["qipuId"];
                                itemData["channelName"] = item["channelName"];
                                itemData["globalPublishDate"] = item["globalPublishDate"];
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            var formatArr = [];
                            formatArr.push(item["id"]);
                            formatArr.push(item["label"]);
                            formatArr.push(item["channelName"]);
                            formatArr.push(item.globalPublishDate);
                            formatArr.push(Program.Util.formatter.purchase(item.isPurchase));
                            formatArr.push(Program.Util.formatter.publishStatus(item.pagePublishStatus));
                            return Program.Util.template.playbackSuggest(formatArr);
                        },
                        header: Program.Util.template.playbackSuggest(Program.Config.Header.playbackSuggest)
                    }
                };

                var defaultHeaderHtml = Program.Util.template.albumSuggest(Program.Config.Header.albumSuggest);

                var videoSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        parseValue: function () {
                            var self = this;
                            var val = this.element.val(),
                                ret = [],
                                items = null,
                                itemData = null,
                                options = self.options;

                            if (val) {
                                items = val.split(';');
                                $.each(
                                    items, function (i, item) {
                                        item = item.split(',');
                                        itemData = {};
                                        itemData[self._showKey] = item[0];
                                        itemData[options.labelKey] = item[1];
                                        itemData[options.valueKey] = item[0];
                                        ret.push(itemData);
                                    }
                                );
                            }
                            this._value('');
                            return ret;
                        },

                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData[self._showKey] = item["qipuId"];
                                itemData["channelName"] = item["channelName"];
                                itemData["copyrightEndTime"] = item["copyrightEndTime"] ? item["copyrightEndTime"] : null;
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return Program.Util.template.templateSuggest(item)
                        },
                        header: defaultHeaderHtml
                    }
                }

                var albumSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        select: function (event, object) {
                            this.value = object.item.id + "";
                            return false;
                        },
                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_album_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData["channelName"] = item["channelName"];
                                itemData["copyrightEndTime"] = item["copyright"] ? item["copyright"][0].copyrightEndTime : null;
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return Program.Util.template.templateSuggest(item)
                        },
                        header: defaultHeaderHtml
                    }
                }

                var playListSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },

                        select: function (event, object) {
                            this.value = object.item.id + "";
                            return false;
                        },

                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_playlist_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["name"];
                                itemData["channelName"] = item["channelName"];
                                itemData["copyrightEndTime"] = "";
                                itemData["isPurchase"] = "";
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return Program.Util.template.templateSuggest(item)
                        },
                        header: defaultHeaderHtml
                    }
                }

                var puyuSuggest = {
                    id: "suggest_barCode",
                    options: {
                        source: EpgWeb.urlConfig.queryPuYu,
                        parseValue: function () {
                            return [];
                        },
                        ignoreWord: true,
                        multiple: false,
                        select: function (event, object) {
                            var flag = formElement.fillPuYuOnClick(object.item);
                            if (flag == true) {
                                $("input[name=puyu_barCode]").val(object.item.value);
                                $("input[name=suggest_barCode]").val(object.item.value);
                            }
                            return false;
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null || json.code != "A00000") {
                                return [];
                            }
                            data = JSON.parse(json.data);
                            $.map(data.cprContents, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["contractId"];
                                itemData[options.labelKey] = $("input[name=suggest_barCode]").val();
                                itemData["contractNumber"] = item["contractNumber"];
                                itemData["videoName"] = item["videoName"];
                                itemData["cprName"] = item["cprName"];
                                itemData["startTime"] = item["startTime"];
                                itemData["endTime"] = item["endTime"];
                                itemData["produceName"] = item["produceName"] || "";
                                itemData["produceTime"] = item["produceTime"] || "";
                                itemData["actors"] = item["actors"] || "";
                                itemData["directors"] = item["directors"] || "";
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        method: "post",
                        getParam: function (term) {
                            return { "barCode": term };
                        },

                        template: function (item) {
                            var formatArr = [];
                            formatArr.push(item["label"]);
                            formatArr.push(item["videoName"]);
                            formatArr.push(item["produceName"]);
                            formatArr.push(item["produceTime"]);
                            formatArr.push(item["actors"]);
                            formatArr.push(item["directors"]);
                            formatArr.push(item["cprName"]);
                            formatArr.push(item["contractNumber"]);
                            formatArr.push(item["startTime"] + "~" + item["endTime"]);
                            return Program.Util.template.puyuSuggest(formatArr)
                        },
                        header: Program.Util.template.puyuSuggest(Program.Config.Header.puyuSuggest)
                    }
                }

                var votePKSuggest = {
                    id: "votePK",
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            return [];
                        },
                        select: function (event, object) {
                            this.value = object.item.id + "";
                            return false;
                        },
                        getParam: function (term) {
                            var requestData = {url: Program.Constant.vote_inner_url, type: "get", params: {title: term, source: 6}};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["voteid"];
                                itemData[options.labelKey] = item["mainTitle"];
                                itemData["createTime"] = item["createTime"] || 0;
                                if (itemData["createTime"] > 0) {
                                    itemData["createTime"] = Program.Util.formatDateTimeFormat(new Date(itemData["createTime"]));
                                } else {
                                    itemData["createTime"] = "";
                                }
                                itemData["title"] = item["mainTitle"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return Program.Util.template.voteSuggest([ item["id"], item["title"], item["createTime"]]);
                        },
                        //    header: defaultVoteHeaderHtml
                        header: Program.Util.template.voteSuggest(Program.Config.Header.voteSuggest)
                    }
                }
                var voteRankSuggest = {
                    id: "voteRank",
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        select: function (event, object) {
                            this.value = object.item.id + "";
                            return false;
                        },
                        parseValue: function () {
                            return [];
                        },
                        getParam: function (term) {
                            var requestData = {url: Program.Constant.vote_inner_url, type: "get", params: {title: term, source: 7}};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["voteid"];
                                itemData[options.labelKey] = item["mainTitle"];
                                itemData["createTime"] = item["createTime"] || 0;
                                if (itemData["createTime"] > 0) {
                                    itemData["createTime"] = Program.Util.formatDateTimeFormat(new Date(itemData["createTime"]));
                                } else {
                                    itemData["createTime"] = "";
                                }
                                itemData["title"] = item["mainTitle"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return Program.Util.template.voteSuggest([ item["id"], item["title"], item["createTime"]]);
                        },
                        header: Program.Util.template.voteSuggest(Program.Config.Header.voteSuggest)
                    }
                }


                var daojuSuggest = {
                    id: "daojuId",
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        select: function (event, object) {
                            this.value = object.item.label + "";
                            $('#daojuTip').html("渠道号: " + object.item.id);
                            return false;
                        },
                        parseValue: function () {
                            return [];
                        },
                        getParam: function (term) {
                            var params = {
                                api_key: 'epg',
                                format: 'json',
                                ip: Program.Constant.daoju_ip,
                                partner_name: term,
                                time: Math.round(new Date().getTime() / 1000),
                                //time: 1459163882,
                                version: '1.0.0'
                            };
                            var paramSign = Program.Util.createSign(params, Program.Constant.daoju_secret);
                            params.sign = paramSign;

                            var requestData = {url: Program.Constant.daoju_inner_url, type: "post",
                                params: params
                            };
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }

                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["partner_code"];
                                itemData[options.labelKey] = item["partner_name"];
                                itemData["add_time"] = item["add_time"];
                                itemData["admin_username"] = item["admin_username"];
                                ret.push(itemData);
                            });
                            return ret.slice(0, 10);
                        },
                        template: function (item) {
                            return Program.Util.template.daojuSuggest([item["id"], item["label"], item["add_time"], item["admin_username"]]);
                        },
                        header: Program.Util.template.daojuSuggest(Program.Config.Header.daojuSuggest)
                    }
                };

                $("#" + qitanSuggest.id).suggest(qitanSuggest.options);
                $("#" + actorSuggest.id).suggest(actorSuggest.options);
                $("#" + playbackSuggest.id).suggest(playbackSuggest.options);
                $("input[name$=_simple-video]").suggest(videoSuggest.options);
                $("input[name$=_album]").suggest(albumSuggest.options);
                $("input[name$=_playlist]").suggest(playListSuggest.options);
                $("#" + puyuSuggest.id).suggest(puyuSuggest.options);
                $("#" + votePKSuggest.id).suggest(votePKSuggest.options);
                $("#" + voteRankSuggest.id).suggest(voteRankSuggest.options);
                $("#" + daojuSuggest.id).suggest(daojuSuggest.options);
            },

            submitHandler: function submitHandler(type) {
                if ($.trim($("#votePK").val()) != "" && $("#votePK").val() != $("#votePK").suggest("getValue")) {
                    EpgWeb.Plugin.showTips({content: "PK投票 不允许手动修改！", type: "error"});
                    return;
                }
                if ($.trim($("#voteRank").val()) != "" && $("#voteRank").val() != $("#voteRank").suggest("getValue")) {
                    EpgWeb.Plugin.showTips({content: "列表投票 不允许手动修改！", type: "error"});
                    return;
                }

                var self = this;
                var modelData = self.prepareModel();
                var channelEntity = self.dao.getChannel();
                if (channelEntity != null) {
                    if (channelEntity.liveType == 2) {
                        if (!self.checkLiveType(modelData)) {
                            return;
                        }
                    }
                }
                if (!self.checkModel(modelData)) {
                    return;
                }
                $("button[name=submitBtn]").prop("disabled", "disabled");
                self.remoteCheck.doCheck(null, function (data) {
                        var allSuccess = true;
                        var errorMsg = [];
                        if (data != null) {
                            $.each(data, function (index, element) {
                                if (!element.success) {
                                    allSuccess = false;
                                    errorMsg.push(element.msg);
                                }
                            });
                        }
                        if (!allSuccess) {
                            EpgWeb.Plugin.showTips({
                                content: errorMsg.join("\n"),
                                type: "error"
                            })
                            $("button[name=submitBtn]").removeAttr("disabled");
                            return;
                        }

                        var sendImageDatas = null;
                        if (self.dao.cfgName.id == 0 || self.dao.cfgName.editPic) {
                            sendImageDatas = self.getSendImageData();
                        }
                        var task = self.task.sendTask(modelData, sendImageDatas);
                        task.regName = type == "edit" ? "editData" : "saveData";
                        task.options.url = type == "edit" ? EpgWeb.urlConfig.programEdit : EpgWeb.urlConfig.programAdd;
                        EpgWeb.ajaxQueue.push(task.regName, task.options, null, true);
                        EpgWeb.ajaxQueue.startLoad();
                    },
                    function startRemoveCheck(saveData) {
                        if (saveData != null) {
                            $.each(saveData, function (index, element) {
                                var requestData = {url: EpgWeb.urlConfig.getQiPuBaseUrl(element.value), type: "get"};
                                $.ajax({
                                    url: EpgWeb.urlConfig.redirect,
                                    type: "post",
                                    dataType: "json",
                                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                                    success: function (data) {
                                        console.log("data" + JSON.stringify(data))
                                        element.complete = true;
                                        if (data != null && data.hasOwnProperty("id")) {
                                            element.success = true;
                                            if (data["episode_summary"] != null && data["episode_summary"].length > 200) {
                                                element.success = false;
                                                element.msg = "奇谱ID：" + element.value + " 关联节目超过200个!";
                                            }
                                        } else {
                                            element.success = false;
                                            element.msg = "验证失败:" + element.value;
                                        }
                                        console.log("element.msg" + element.msg);
                                    },
                                    error: function (data) {
                                        element.complete = true;
                                        element.success = false;
                                        element.msg = "检测请求失败:" + element.value;
                                        console.log("data" + JSON.stringify(data) + ";" + element.msg)
                                    }
                                })
                            })
                        }
                    }
                )
            },
            checkLiveType: function (modelData) {
                var checkArr = [];
                checkArr.push({value: $('#playbackSuggest').val().length, error: "关联直转点后节目Id不能为空", type: "gt", other: 0 })
                checkArr.push({value: $('#episodeGrade').val().length, error: "节目等级不能为空", type: "gt", other: 0 });
                checkArr.push({value: $("input:radio[name=use_puyu_radio]:checked").val(), error: "必须选择关联璞玉信息", type: "not_empty" });
                if ($("input:radio[name=use_puyu_radio]:checked").val() == 1) {
                    checkArr.push({value: $("input[name=suggest_barCode]").val().length, error: "尚未设置关联璞玉信息", type: "gt", other: 0 });
                    checkArr.push({value: $("input[name=suggest_barCode]").val(), error: "璞玉条形码与数据不一致", type: "eq", other: $("input[name=puyu_barCode]").val() });
                    modelData.barCode = $("input[name=puyu_barCode]").val();
                }
                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt checkLiveType checkRepeat")
                    return false;
                }
                var checkLevel1 = false;
                var checkLevel2 = false;
                var checkLevel3 = false;
                var hasThirdCategory = $("input[name=third_category]");
                if (hasThirdCategory.length == 0) {
                    checkLevel3 = true;
                }
                if (modelData.categoryCheck != null) {
                    $.each(modelData.categoryCheck, function (i, element) {
                        if (element.level == 1) {
                            checkLevel1 = true;
                        }
                        if (element.level == 2) {
                            checkLevel2 = true;
                        }
                        if (element.level == 3) {
                            checkLevel3 = true;
                        }
                    })
                    delete modelData.categoryCheck;
                }
                //if (!checkLevel2) {
                //    EpgWeb.Plugin.showTips({content: "必须选择一个二级分类", type: "error"});
                //    return false;
                //}
                //if (!checkLevel3) {
                //    EpgWeb.Plugin.showTips({content: "必须选择一个三级分类", type: "error"});
                //    return false;
                //}
                return true;
            },

            checkModel: function (modelData) {
                var self = this;
                self.remoteCheck.clear();
                var checkArr = [];
                var frontValue = $("select[name=frontSuggestType]").val();
                var endValue = $("select[name=endSuggestType]").val();
                var items = null;
                if (frontValue == "simple-video") {
                    items = $('#appendFront_' + frontValue).suggest("getItems");
                    checkArr.push({value: items.length, error: "数量不能大于200", type: "le", other: 200})
                } else {
                    if ($('#appendFront_' + frontValue).val().length > 0) {
                        checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "节目集锦需要数字格式", type: "number"});
                        if ("album" == frontValue) {
                            checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "专辑qipuId格式错误", type: "endsWith", other: "01"});
                        } else if ("playlist" == frontValue) {
                            checkArr.push({value: $('#appendFront_' + frontValue).val(), error: "播单qipuId格式错误", type: "endsWith", other: "02"});
                        }
                        self.remoteCheck.addToCheck({regName: '#appendFront_' + frontValue, value: $('#appendFront_' + frontValue).val(), modeType: frontValue })
                    }

                }
                if (endValue == "simple-video") {
                    items = $('#appendEnd_' + endValue).suggest("getItems");
                    checkArr.push({value: items.length, error: "数量不能大于200", type: "le", other: 200})
                } else {
                    if ($('#appendEnd_' + frontValue).val().length > 0) {
                        checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "节目集锦需要数字格式", type: "number"})
                        if ("album" == frontValue) {
                            checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "专辑qipuId格式错误", type: "endsWith", other: "01"});
                        } else if ("playlist" == frontValue) {
                            checkArr.push({value: $('#appendEnd_' + frontValue).val(), error: "播单qipuId格式错误", type: "endsWith", other: "02"});
                        }
                        self.remoteCheck.addToCheck({regName: '#appendEnd_' + frontValue, value: $('#appendEnd_' + frontValue).val(), modeType: frontValue })
                    }
                }
                if ($('#playbackSuggest').val().length > 0) {
                    if ($('#playbackSuggest').val() !== '0') {
                        checkArr.push({value: $('#playbackSuggest').val(), error: "关联直转点需要数字格式", type: "number"})
                        checkArr.push({value: $('#playbackSuggest').val(), error: "节目qipuId格式错误", type: "endsWith", other: "00"});
                    }
                }
                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt checkRepeat")
                    return false;
                }

                checkArr = [];
                checkArr.push({value: [modelData.streamStartPlayTime, modelData.streamEndPlayTime, modelData.startPlayTime, modelData.endPlayTime, modelData.pname], error: "请填写完整", type: "not_empty"});
                checkArr.push({value: [modelData.startPlayTime, modelData.endPlayTime, modelData.streamStartPlayTime, modelData.streamEndPlayTime], error: ["节目开始时间日期格式错误", "节目结束时间日期格式错误", "流开始时间日期格式错误", "流结束时间日期格式错误"], type: "date"});
                //   checkArr.push({value: modelData.pname.length, error: "节目名称长度不能超过40", type: "le", other: 40 })
                checkArr.push({value: modelData.endPlayTime, error: "节目结束时间需要大于节目开始时间", type: "gt", other: modelData.startPlayTime});
                checkArr.push({value: modelData.streamEndPlayTime, error: "流结束时间需要大于流开始时间", type: "gt", other: modelData.streamStartPlayTime});
                checkArr.push({value: modelData.streamEndPlayTime, error: "流结束时间不能小于节目结束时间", type: "ge", other: modelData.endPlayTime});
                checkArr.push({value: modelData.streamStartPlayTime, error: "流开始时间不能大于节目开始时间", type: "le", other: modelData.startPlayTime});
                checkArr.push({value: modelData.subjectUrl, error: "专题页url格式错误,请修改后保存!", type: "self_design", checkCall: function (checkData, checkValue) {
                    if (checkValue == null || checkValue.length == 0) {
                        return true;
                    }
                    return checkValue.split('://')[0] === 'http';
                }});
                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt checkRepeat")
                    return false;
                }
                var channelEntity = self.dao.getChannel();
                var checkProgram = (new Date(modelData.endPlayTime.replace(/-/g, "/")).getTime() - new Date(modelData.startPlayTime.replace(/-/g, "/")).getTime()) / 1000;
                if (channelEntity.maxPlaybackPeriod < checkProgram) {
                    console.log("checkProgram:" + checkProgram + ";maxPlaybackPeriod:" + channelEntity.maxPlaybackPeriod);
                    SystemDialog.queryAlert("回看时间必须大于或等于节目时间<br>无法完成提交，请先修改回看时间！");
                    return false;
                }
                return true;
            },

            getSendImageData: function () {
                var self = this;
                var sumbitImgData = {};
                sumbitImgData.imageDatas = [];
                var imageData = {"materials": [], "images": [], "contentRank": "0", "useType": "699"}
                sumbitImgData.imageDatas.push(imageData);
                var cropValues = $("#AlbumEditScreenCorp").data('imageCrop').getValue();
                console.log(JSON.stringify(cropValues));
                $(".item img").each(function (i, imgTarget) {
                    imageData.materials.push(self.getFormatMaterial($(imgTarget)))
                });
                for (var key in cropValues) {
                    imageData.images.push(self.getFormatCrop(cropValues[key]))
                }
                if (imageData.materials.length == 0 && imageData.images.length == null) {
                    return null;
                }
                return sumbitImgData.imageDatas;
            },


            getFormatMaterial: function ($target) {
                return {
                    "area": "bj",
                    //   "area": "sh",
                    "fromType": "0",
                    "location": $target.data("spath"),
                    "width": $target.data("width"),
                    "height": $target.data("height")
                }
            },
            getFormatCrop: function (cropTarget) {
                return {
                    "materialLocation": cropTarget.spath,
                    "editInfo": {
                        "cutPosition": [cropTarget.x1, cropTarget.y1, cropTarget.y2 - cropTarget.y1, cropTarget.x2 - cropTarget.x1].join(","),
                        "scale": cropTarget.w + ":" + cropTarget.h
                    }
                }
            },

            makeUpCategory: function () {
                var category = [];
                var rootId = Number($("#channelCateTag").val());
                category.push({id: rootId, level: 1 });
                var secArr = $("input[name=sec_category]:checked");
                var jElement = null;
                $.each(secArr, function (i, element) {
                    jElement = $(element);
                    category.push({id: parseInt(jElement.val()), pid: rootId, name: jElement.attr("data-name"), level: 2});
                });

                var thirdArr = $("input[name=third_category]:checked");
                $.each(thirdArr, function (i, element) {
                    jElement = $(element);
                    category.push({ pid: parseInt(jElement.attr("data-pid")), id: jElement.val(), name: jElement.attr("data-name"), level: 3});
                });
                return category
            },

            initDialog: function () {
                var self = this;
                $("#oepn-item-dlg").dialog({
                    title: "提示",
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                })
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                $("button[name=con_created]").bind("click", function (event) {
                    $("#oepn-item-dlg").dialog("close");
                    self.submitHandler("save", true);
                })
                $("button[name=con_cancel]").bind("click", function (event) {
                    $("#oepn-item-dlg").dialog("close");
                })
            },
            initEditPicZone: function () {
                Program.FileUpload.initEditPicZone()
            },
            bindValidate: function () {
                var self = this;
                var channelEntity = self.dao.getChannel();
                if (channelEntity != null && channelEntity.liveType == 2) {
                    $("input[name=passport_uid]").bind("focusout", function (event) {
                        var curTarget = $(event.currentTarget);
                        var $sec_curTarget = curTarget.val();
                        var helpblock = curTarget.parent().find("span");
                        self.doPassPortClean(helpblock, curTarget);
                        if (!/^[0-9]*$/.test($sec_curTarget)) {
                            self.doPassPortError(helpblock, curTarget, "请输入数字");
                            return
                        }
                        if ($.trim($sec_curTarget).length == 0) {
                            return;
                        } else {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_passport_url, type: "get", params: {uid: $sec_curTarget }, needCookie: true};
                            $.ajax({
                                url: EpgWeb.urlConfig.redirect,
                                type: "post",
                                dataType: "json",
                                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                                success: function (data) {
                                    if (data != null) {
                                        if ("A00000" == data.code) {
                                            self.doPassPortSuc(helpblock, data.data);
                                        } else {
                                            if (data.msg.indexOf("指定的uid不存在") != -1) {
                                                data.msg = "uid不存在,请重新输入";
                                            }
                                            self.doPassPortError(helpblock, curTarget, data.msg);
                                        }
                                    } else {
                                        self.doPassPortError(helpblock, curTarget)
                                    }
                                },
                                error: function (data) {
                                    self.doPassPortError(helpblock, curTarget)
                                }
                            })
                        }
                    });
                    $("input[name=passport_nickname]").bind("focusout", function (event) {
                        var curTarget = $(event.currentTarget);
                        var $sec_curTarget = curTarget.val();
                        var helpblock = curTarget.parent().find("span");
                        self.doPassPortClean(helpblock, curTarget);
                        if ($.trim($sec_curTarget).length == 0) {
                            return;
                        } else {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_passport_url, type: "post", params: {nickname: $sec_curTarget }, needCookie: true};
                            $.ajax({
                                url: EpgWeb.urlConfig.redirect,
                                type: "post",
                                dataType: "json",
                                data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                                success: function (data) {
                                    if (data != null) {
                                        if ("A00000" == data.code) {
                                            self.doPassPortSuc(helpblock, data.data);
                                            $("input[name=passport_nickname]").val(data.data.userinfo.nickname);
                                        } else {
                                            if (data.msg.indexOf("用户不存在") != -1) {
                                                data.msg = "昵称不存在,请重新输入";
                                            }
                                            self.doPassPortError(helpblock, curTarget, data.msg);
                                        }
                                    } else {
                                        self.doPassPortError(helpblock, curTarget)
                                    }
                                },
                                error: function (data) {
                                    self.doPassPortError(helpblock, curTarget)
                                }
                            })
                        }
                    })
                }
            },
            doPassPortClean: function (helpblock, curTarget) {
                helpblock.html("");
                $("input[name=uid_hidden]").val("");
                $("input[name=nickname_hidden]").val("");
                $("#passport_div").removeClass("error");
                curTarget.removeClass("help-block");
            },

            doPassPortSuc: function (helpblock, data) {
                helpblock.html("");
                $("input[name=uid_hidden]").val(data.userinfo.uid);
                $("input[name=nickname_hidden]").val(data.userinfo.nickname);
            },

            doPassPortError: function (helpblock, curTarget, msg) {
                if (msg == null) {
                    msg = "请求发生异常!"
                }
                helpblock.show();
                helpblock.html(msg);
                $("#passport_div").addClass("error");
                curTarget.addClass("help-block");
            },

            fillRelationData: function (relationEntityList) {
                var self = this;
                var nameArr = "base1Arr,base3Arr,base4Arr,base5Arr,base6Arr,base7Arr,base106Arr,base107Arr".split(",");
                var relationObj = {};
                $.each(nameArr, function (index, paramName) {
                    relationObj[paramName] = [];
                })

                var passportData = {uid: "", nickname: ""};
                var itemModel = null;
                if (relationEntityList != null && relationEntityList.length > 0) {
                    $.each(relationEntityList, function (index, element) {
                        itemModel = {};
                        itemModel.id = element.key;
                        itemModel.label = element.value;
                        switch (element.type) {
                            case 1:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            case 7:
                            case 106:
                            case 107:
                                relationObj["base" + element.type + "Arr"].push(itemModel);
                                break;
                            case 201:
                                $("select[name=live_temp_other]").val(element.value)
                                break;
                            case 301:
                                passportData.uid = element.value;
                                if (element.key == 1) {
                                    passportData.key = "uid";
                                }
                                break;
                            case 302:
                                passportData.nickname = element.value;
                                if (element.key == 1) {
                                    passportData.key = "nickname";
                                }
                                break;
                        }
                    })
                }
                self.addMultipleItem(relationObj["base1Arr"], '#ajaxSuggest', false);
                self.addSingleItem(relationObj["base7Arr"], '#playbackSuggest');
                self.addSingleItem(relationObj["base106Arr"], '#votePK');
                self.addSingleItem(relationObj["base107Arr"], '#voteRank');
                $.each(relationObj["base3Arr"], function (index, target) {
                    var $addBtn = $("#addndelSample3").find("button[class='btn add blue-btn']");
                    $addBtn.parent().find("input[name=base_3_team]").val(target.label);
                    $addBtn.parent().find("input[name=base_3_score]").val(target.id);
                    $addBtn.click()
                })
                var idType = null;
                var base5Arr = relationObj["base5Arr"];
                var base6Arr = relationObj["base6Arr"];
                if (base5Arr.length > 0) {
                    itemModel = base5Arr[0]
                    idType = self.checkIdType(itemModel.id + "");
                    if (idType != null) {
                        $("select[name=frontSuggestType]").val(idType);
                        if (idType == "simple-video") {
                            self.addMultipleItem(base5Arr, '#appendFront_' + idType, true);
                        } else {
                            self.addSingleItem(base5Arr, '#appendFront_' + idType);
                        }
                    }
                }
                if (base6Arr.length > 0) {
                    itemModel = base6Arr[0]
                    idType = self.checkIdType(itemModel.id + "")
                    if (idType != null) {
                        $("select[name=endSuggestType]").val(idType);
                        if (idType == "simple-video") {
                            self.addMultipleItem(base6Arr, '#appendEnd_' + idType, true);
                        } else {
                            self.addSingleItem(base6Arr, '#appendEnd_' + idType);
                        }
                    }
                }

                // init passport id ;
                self.initPassportId(passportData);
            },

            initPassportId: function (passportData) {
                $("input[name=uid_hidden]").val(passportData.uid);
                $("input[name=nickname_hidden]").val(passportData.nickname);
                $("select[name=passport_select]").val("option_" + passportData.key);
                $("input[name=passport_" + passportData.key + "]").val(passportData[passportData.key]);
            },
            addSingleItem: function (dataArr, regName) {
                if (dataArr.length > 0) {
                    dataArr[0].label = "" + dataArr[0].id;
                    $(regName).suggest("setValue", dataArr[0]);
                }
            },

            addMultipleItem: function (dataArr, regName, showKey) {
                showKey = showKey ? true : false;
                $.each(dataArr, function (index, target) {
                    if (showKey) {
                        target["$$autocompleteShowKey"] = target.id;
                    }
                    $(regName).suggest("addValue", target);
                })
            },

            checkIdType: function (idStr) {
                var endStr = idStr.substr(idStr.length - 2)
                switch (endStr) {
                    case "00":
                        return "simple-video";
                    case "01":
                        return "album";
                    case "02":
                        return "playlist";
                    default :
                        return null;
                }
            },

            queryForLvOne: function (params) {
                var self = this;
                var requestData = {url: EpgWeb.Constant.thirdUrl_category_first_list_url, type: "get", params: params, needCookie: true};
                var option = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        $("#secTagZone").html("");
                        if (data != null && data.data != null && data.data.channelData != null) {
                            self.queryForLvSec(data.data)
                        } else {
                            $("#secTagZone").html("没有数据");
                        }
                    },
                    error: function (data) {
                        $("#secTagZone").html("数据加载失败");
                    }
                }
                $.ajax(option)
            },

            queryForLvSec: function (responseData) {
                var self = this;
                var params = null;
                var requestData = null;
                self.remoteCheck.doCheck(responseData.channelData, function (data) {
                    console.log("Program.RemoteCheck.doCheck queryForLvSec")
                    $("input[name$=sec_category]").bind("click", function (event) {
                        var $sec_curTarget = $(event.currentTarget);
                        if ($sec_curTarget.prop("checked") == true) {
                            self.queryForLvThird({channelId: $sec_curTarget.attr("data-channel-id"), id: $sec_curTarget.val(), liveDisplay: 1, liveUsed: 1 })
                            console.log("wait to add $third_curTarget")
                        } else {
                            $("#thirdTagZone input[data-pid=" + $sec_curTarget.val() + "]").parent().remove();
                            console.log("wait to remove $third_curTarget");
                            self.updateThirdTagDiv();
                        }
                    })
                    var programEntity = self.dao.getProgram();
                    if (programEntity != null && programEntity.category != null) {
                        var toParent = $("#secTagZone");
                        $.each(programEntity.categoryArr, function (i, element) {
                            if (element.level == 2) {
                                toParent.find("input[value=" + element.id + "]").click();
                            }
                        })
                    }

                }, function startHandler(saveData) {

                    $.each(saveData, function (i, element) {
                        params = {channelId: responseData.channelId, id: element.categoryId, liveDisplay: 1, liveUsed: 1 };
                        requestData = {url: EpgWeb.Constant.thirdUrl_category_child_list_url, type: "get", params: params, needCookie: true};
                        $.ajax({
                            url: EpgWeb.urlConfig.redirect,
                            type: "post",
                            dataType: "json",
                            data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                            success: function (data) {
                                element.complete = true;
                                if (data == null || data.length == 0) {
                                    console.log("queryForLvSec 没有获得数据");
                                    return;
                                }
                                if (data.length > 0) {
                                    var toParent = $("#secTagZone");
                                    $.each(data, function (i, element) {
                                        $('<label style="display: inline;margin-left: 5px"><input type="checkbox" data-channel-id="' + params.channelId + '" name="sec_category" data-name="' + element.name + '" value="' + element.id + '">' + element.name + '</label>').appendTo(toParent)
                                    });
                                }
                            },
                            error: function (data) {
                                element.complete = true;
                                console.log("queryForLvSec error")
                            }
                        })

                    });
                });
            },

            updateThirdTagDiv: function () {
                var hasThirdCategory = $("input[name=third_category]");
                if (hasThirdCategory.length > 0) {
                    $("#thirdTagDiv").show();
                } else {
                    $("#thirdTagDiv").hide();
                }
            },

            queryForLvThird: function (params) {
                var self = this;
                console.log("Program.RemoteCheck.doCheck queryForLvThird")
                var requestData = {url: EpgWeb.Constant.thirdUrl_category_child_list_url, type: "get", params: params, needCookie: true};
                var programEntity = self.dao.getProgram();
                var options = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        if (data == null || data.length == 0) {
                            console.log(" queryForLvThird 没有获得数据");
                        } else {
                            var htmlArr = [];
                            var toParent = $("#thirdTagZone");
                            $.each(data, function (i, element) {
                                $('<label style="display: inline;margin-left: 5px"><input type="checkbox" data-name="' + element.name + '" data-pid="' + element.pid + '" name="third_category" value="' + element.id + '">' + element.name + '</label>').appendTo(toParent);
                            });
                            if (programEntity != null && programEntity.category != null) {
                                $.each(programEntity.categoryArr, function (i, element) {
                                    if (element.level == 3) {
                                        toParent.find("input[value=" + element.id + "]").prop("checked", true);
                                    }
                                })
                            }
                        }
                        self.updateThirdTagDiv();
                    },
                    error: function (data) {
                        if (data == null) {
                            console.log("queryForLvThird 没有获得数据 error");
                            return;
                        }
                    }
                }
                $.ajax(options);
            }


        })
    }
);
define('../entrance_programEdit/Program.FileUpload',['require','exports','module'],function (require, exports, module) {
    Program.FileUpload = (function(){
        var $imgcrop = null;
        var constant = {
            uploadUrl: "http://upload.iqiyi.com/image_upload",
            requestUrl: "http://upload.iqiyi.com/request_image_upload",
            file: null
        }

        function getGallery() {
            var $gallery = $imgcrop.find(".gallery");
            return $gallery;
        }

        function getObjectURL(file) {
//            var url = null;
//            if (window.createObjectURL !== undefined) { // basic
//                url = window.createObjectURL(file);
//            } else if (window.URL !== undefined) { // mozilla(firefox)
//                url = window.URL.createObjectURL(file);
//            } else if (window.webkitURL !== undefined) { // webkit or chrome
//                url = window.webkitURL.createObjectURL(file);
//            }
//            return url;
            return Com.file.getObjectURL(file);
        }

        function startUpload(file) {
            var imgsrc, $imgdiv, $bardiv;
            file.uid = Com.string.createUUID();
            imgsrc = getObjectURL(file);
            $bardiv = $('<div class="progress progress-info"><div class="bar" style="width: 0%" /></div>');
            $imgdiv = $('<img class="loading" src="' + imgsrc + '" />');
            $imgdiv.data('loading', true).load(function (e) {
                Com.Image.procThumbnail($(this), 128, 80);
                $(this).unbind('load');
            });
            var $gallery = getGallery();
            $gallery.append($('<li class="item img-' + file.uid + '" />').append($imgdiv, $bardiv));
        }

        function qichuanRequestFile(options, callback) {
            options = options || {};
            constant.file = options.file;
            var headers = options.headers || {};
            $.ajax({
                url: constant.requestUrl + '?t=' + new Date().getTime(),
                dataType: 'json',
                headers: headers,
                method: 'get',
                success: function (data) {
                    if (data && data.code == 'A00000') {
                        callback.call(this, data);
                    } else {
                        console.log('get access fail.');
                        callback.call(this, data);
                    }
                },
                error: function (data) {
                    callback.call(this, data);
                }
            });
        }

        function qichuanUploadFile(options, callback) {
            var fileDetail = constant.file;
            fileDetail.file_id = options.data.file_id;
            var params = {
                url: constant.uploadUrl,
                file: fileDetail,
                headers: {
                    file_id: fileDetail.file_id,
                    file_size: fileDetail.size,
                    range: ('0' + '-' + (fileDetail.size - 1) + ''),
                    businessType: fileDetail.type.split("/")[0]
                }
            };
            var formData = new FormData();
            formData.append('businessType', params.headers['businessType']);
            formData.append('fileid', params.headers['file_id']);
            formData.append('imagefile', params.file);

            $.ajax({
                url: params.url,
                method: "post",
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (request) {
                    request.setRequestHeader("file_id", params.headers.file_id);
                    request.setRequestHeader("file_size", params.headers.file_size);
                    request.setRequestHeader("range", params.headers.range);
                    request.setRequestHeader("businessType", params.headers.businessType);
                },
                xhr: function () {        //这是关键  获取原生的xhr对象  做以前做的所有事情
                    var xhr = jQuery.ajaxSettings.xhr();
                    xhr.upload.onload = function () {
                        var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                        $imgdiv.remove();
                        //$('.button-manual').attr('disabled','disabled');
                        //$('input.uploadButton').attr('disabled','disabled');
                    }

                    xhr.upload.onprogress = function (ev) {
                        if (ev.lengthComputable) {
                            var percent = Math.floor(100 * ev.loaded / ev.total);
                            var $imgdiv = getGallery().find('li.img-' + fileDetail.uid);
                            $imgdiv.find('div.bar').width(percent + '%');
                            if (percent == 100) {
                                $imgdiv.find('div.progress').remove();
                            }
                        }
                    }
                    return xhr;
                },
                data: formData,
                dataType: "json",
                success: function (data) {
                    if (data.code == "A00000") {
                        console.log("success upload");
                        callback.call(this, data);
                    }
                }
            })
        }


        function requestOver(data) {
            console.log("request file:" + data);
            if (data.code == 'A00000') {
                qichuanUploadFile(data, uploadOver);
            } else {
                console.log(data.msg);
            }
        }

        function uploadOver(data) {
            if (data.code == 'A00000') {

                $imgcrop.imagecrop("addImages", [
                    {url: data.data.httpInnerUrl, "spath": data.data["file_path"]}
                ]);
                var $uploadBtn = $imgcrop.find('input.uploadButton');
                $uploadBtn.val("");
            } else {
                console.log(data.msg);
            }
        }

        function doInit($target){
          //  var $imgcrop = $("#AlbumEditScreenCorp");
            $imgcrop = $target;
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $slideshow = $imgcrop.find('.slideshow');
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            $imgcrop.imagecrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            $uploadBtn.val("");
            $uploadBtn.bind("click", function (event) {
                console.log("click");
            })
            $uploadBtn.bind("change", function (event) {
                var file = $uploadBtn[0].files[0];
                var url = Com.file.getObjectURL(file)
                var checkFileType = Com.file.getExt(file.name);
                var acceptTypes = $uploadBtn[0].accept
                if (acceptTypes.indexOf("." + checkFileType) == -1) {
                    showTips({
                        content: "只允许提交类型为" + acceptTypes + "的文件",
                        type: "error"
                    })
                    return;
                }
                if (file.size > 1024 * 1024 * 5) {
                    showTips({
                        content: "上传文件大小不能超过5M",
                        type: "error"
                    })

                    return;
                }
                var headers = {
                    businessType: "image",
                    filesize: file.size,
                    role: "epg_image",
                    filetype: Com.file.getExt(file.name),
                    producttype: "ppc",
                    Location: "sh"
                }

                var options = {
                    headers: headers,
                    file: file
                };
                startUpload(file);
                qichuanRequestFile(options, requestOver);
            })
        }

        function initEditPicZone(){
            var picEnity = null;
            if (Program.Dao.cfgName.id == 0) {
                if (Program.Dao.cfgName.fatherId > 0) {
                    picEnity = Program.Dao.getChannel();
                    if (picEnity != null && picEnity.liveType != 2) {
                        picEnity = null;
                    }
                }
            } else {
                picEnity = Program.Dao.getProgram();
            }
            if (picEnity == null || picEnity.logoUrl == null || picEnity.logoUrl == "") {
                return;
            }
            var demoData = {"imageDatas": JSON.parse(picEnity.logoUrl) };
            if (demoData.imageDatas.length == 0) {
                return;
            }
            var materials = [];
            $.each(demoData.imageDatas[0].materials, function (index, element) {
                materials.push({url: element.url, spath: element.location, id: element.id, data: { id: element.id }});
            })
            var elementValue = {};
            $.each(demoData.imageDatas[0].images, function (index, element) {
                var plusData = {};
                var position = element.editInfo.cutPosition.split(",");
                elementValue[element.editInfo.scale.replace(":", "-")] = plusData;
                plusData.x1 = parseInt(position[0]);
                plusData.x2 = parseInt(position[0]) + parseInt(position[3]);
                plusData.y1 = parseInt(position[1]);
                plusData.y2 = parseInt(position[1]) + parseInt(position[2]);
                plusData.spath = element.materialLocation;
                $.each(demoData.imageDatas[0].materials, function (index, originalImg) {
                    if (element.materialLocation == originalImg.location) {
                        plusData.imgsrc = originalImg.url;
                        return false;
                    }
                })
                plusData.data = {};
            })
            $imgcrop.imagecrop("addImages", materials, function () {
                $imgcrop.imagecrop("setValue", elementValue);
            });
        }

        return {

            startUpload: startUpload,
            doInit:doInit,
            initEditPicZone:initEditPicZone
        }
    })()


});
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'enter', [
        "../entrance_ticket/Ancestor",
        "../entrance_ticket/Ancestor.Auth",
        "../entrance_ticket/Ancestor.Grid",
        "../entrance_ticket/Ancestor.Config",
        "../entrance_ticket/Ancestor.Util",
        "../entrance_ticket/Ancestor.Dao",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../entrance_programEdit/Program",
        "../entrance_programEdit/Program.Action",
        "../entrance_programEdit/Program.Config",
        "../entrance_programEdit/Program.Dao",
        "../entrance_programEdit/Program.Util",
        "../entrance_programEdit/Program.Task",
        "../entrance_programEdit/Program.Edit",
        "../entrance_programEdit/Program.FileUpload"
    ],

    function() {
        console.log('ticket load done:', 'enter');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }
);

